How to create a view page to save two objects in cakePHP - cakephp

I have two models
Address:firstline,secondline
Contact:firstname,lastname
and database tables address and contact respectively. i have to create a view page which should display like below format
first name:
last name:
Address:
First line:
second Line:
NEXT STEP {this button leads to next page}
How to create this view.please explain me with the code
and how to save both the objects in the session after clicking on next step button.and what are the controllers to be written.explain me with the code.

address_controller.php
class AddressController extends AppController {
var $uses = array('Address', 'Contact');
the above will allow you access to the Contact Model from the Address Controller
then you can save the data from your add function into both tables
$addressData = array(
'id'=>'',
'firstline'=>$this->data['Address']['firstline'],
'secondline'=>$this->data['Address']['secondline'],
'contact_id'=>$this->Auth->user('id')
);
Then save the data with the following code....
$this->Address->save($addressData);
I would recommend that you do a check to make sure that the data actually saved and then proceed onto the normal save method for the Contact model.
if you already have the add.ctp created for the Address and Contact Models, then you can just go to your views->address->add.ctp and copy the form fields and paste them into the views->contact->add.ctp form.
without seeing any of your code, it's hard to tell exactly what your fields will be but should look something like this :
<input name="data[Contact][firstname]">
<input name="data[Contact][lastname]">
<input name="data[Address][firstline]">
<input name="data[Address][secondline]">

Related

AngularJS - memorizing chosen values in form after returing from some special state (view)

I build some form analogously to:
http://tutorials.jenkov.com/angularjs/forms.html
It means that I also use ng-model as chosen value. These values are retrieved from database - there are multiselect options.
<form>
<input type="text" name="firstName" ng-model="myCtrl.firstName"> First name <br/>
<input type="text" name="lastName" ng-model="myForm.lastName"> Last name <br/>
</form>
Controller {
constructor() {
this.firstName = getFirstNameFromDatabase();
}
}
It is sketch of my code - I wouldn't like to show it here.
It is working ok - values are retrieved from database and displayed as proposition in form.
My issue is following:
Let's assume that someone type in this form "abc". Then, someone click button next (it direct to another state, user is directed to another view - lets denote it X).
User can return from X view with back button. I would like to display "abc" (so my app should memorize chosen values).
However, if user type value "abc" and return to menu (or another else state (view) - different from next button) - in this case value shouldn't be memorized.
Can you give me some clues ?
Since you're actually switching pages in your application, you're going to have to put their content in some sort of persistent storage. A couple ideas pop into my head.
Temporary Browser Storage / Cookies
Server-side storage in a Database or Cache
Either way, you'll need to store the data whenever the user manipules the values. And when they switch pages, choose whether to clear the data or not based on whether it's your special view.
Or another idea is to use an angular function to change the url (rather than a simple anchor). Then in that function you can persist the data before switching to your view. But if they go to a different page, it won't get saved. This only works if they navigate based on your page's links.
Usually this sort of thing is accomplished using a single page which includes both your original view and the next view. You can swap out the content using JS so the user doesn't know the difference. So that's still an option too.

Angularjs step by step form

I am trying to create exactly same form given in this fiddle
steb by step angular form
but whenever i click on the next button data entered in the first step resets.. how can i prevent this? On submit all data is undefined while reading in javascript.
Please help me..
In the JsFiddle code you provided you are not retaining the users data, meaning that data is being Binded to anything in the controller. So when leave the section the data is removed.
To retain data make the following changes:
// In your controller add the following object to the $scope
$scope.user = {}
// In your HTML code add the following to your input fields
<input type="text" id="teamName" ng-model="user.teamName" placeholder="Team Name" />
Notice the ng-model tag in the input field this is what binds your data to the user object within your controller
Heres a working JsFiddle, please note that I only updated the Team Name field. Type something in the Team Name field and go to the next section and it will retain your data. You will need to update the remaining fields.

Angularjs : creating dynamic form

I'm developing a friend invitation feature for a website.
Only requirements are : by email and has a max number of invitations at a time.
My idea is the following :
At the start, user only sees one email field. When he enters an email adress in the only field, angularjs validates it (email format check) and creates an additional email field.
Now, I come from a jquery background and I think it's bad practice to manipulate DOM with angular.
How would one do it with angularjs ?
Is it a good idea to create a factory that "produces" (from a template file) fields ?
Can a library like bootstrap ui help me write simpler code for form validation and error management
This Plunker might fulfill your need at its closest: http://plnkr.co/edit/5qRXQ1XGzUnhYjLCiyYR?p=preview
The key point in this technique is letting the user directly edit a dynamic list of models. Indeed in the example, $scope.invites contains your values. The trick here is referring to them as models:
<input type="email" class="invite" name="invite{{ $index }}" ng-model="invites[$index].mail" ng-change="checkInvite($index)" />
$index being the index of the current ng-repeat iteration. checkInvite function will take care of watching changes in your invites fields.
Notes:
invites is an array of objects, this way we're sure not to mess with ng-repeat, iterating over the reference that we handle (vs models that would be handled by angular)
The field's name is useful to manually check the field's validity: in the controller we can check a field's validity accessing $scope.formName.fieldName.$valid
I also added an extra test that checks if the user clears a non-last filled-in field. In this case, we remove the field.
Have fun using angular!
Personally, I would find the design confusing, since I wouldn't know I could have more email addresses. At the minimum, I would want a + to indicate to the user that s/he can add more addresses. Think of how airlines do "multiple destinations" searches on their Websites.
However, if you are set at this, use an array in the scope. I am using a table for this, but anything will do.
<input ng-model="newemailaddress"></input><button ng-click="addEmail">Add</button>
<table>
<tr ng-repeat="addr in addresses"><td>{{addr}}</td></tr>
</table>
And your controller something like:
.controller('MyCtrl',function($scope) {
$scope.addresses = [];;
$scope.newemailaddress = "";
$scope.addEmail = function() {
// do validation
if (valid) {
$scope.addresses.push($scope.newemailaddress);
$scope.newemailaddress = "";
};
};
})

web2py - Dropdown menu

I'm trying to have a dropdown menu for the user to select the database table. I have defined few tables in db.py and I want the user the to select a particular table from a dropdown menu and insert entries. Right now I use SQLFORM:
def index():
form=SQLFORM(db.selectedtable) #want to change the table name#
if form.process().accepted:
response.flash = 'form accepted'
elif form.errors:
response.flash = 'form has errors'
else:
response.flash = 'please fill out the form'
return dict(form=form)
I need the user to select 'selectedtable' value from a dropdown list that shows all the available tables in the DB. I do not necessarily want to retrieve the table values from DB. I am OK with defining a list with the available tables and the dropdown menu can pull the table names from that list.
So far I only found IS_IN_DB to automatically create a dropdown and PluginDropdown() but that does not serve my purpose. If soemebody can direct me to the proper way of handling this task I'd be really thankful.
Regards.
Update:
After Anthony's suggession I tried the following with , as I'm not that familiar with JS.
{{extend 'layout.html'}}
{{select='NONE'}}
<form>
<select>
{{for item in TOOLS:}}
<option value="{{select=item}}">{{=item}}</option>{{pass}}
</select>
<input type="submit" value="Go!"/>
</form>
<h2>Input form</h2>
{{=form}}
<h2>{{=select}}</h2>
As you might see this doesn't work properly. What I tried to do is to get the user chose value to 'select' variable. But it doesn't work. It always gets the last element in ITEMS (this list is defined in db.py). My next option would be to be call another controller function, passing the user selected value as an argument. Then it can prepare the form with the passed value and send to a view to display
<h2>Input form</h2>
{{=form}}
But I'm not sure how I can assign the user chosen value to an argument and then call another controller function with that arugument value.
If you have any suggestion how I can modify this to get the user chosen value thats very much appreciated. Thank you.
You could create a <select> element listing all the tables, and then load the form associated with the selected table as a web2py component via Ajax. In the view of the main page (e.g., /views/default/index.html):
<script>
jQuery(function() {
jQuery('#table').change(function() {
web2py_component("{{=URL('default', 'form.load')}}" + "/" +
jQuery(this).val(), target='form')
})
})
</script>
{{=SELECT('Select a table', *db.tables, _id='table')}}
<div id="form"></div>
And in a controller (e.g., default.py):
def form():
if request.args(0) in db.tables:
response.generic_patterns = ['load']
return dict(form=SQLFORM(db[request.args(0)]).process())
else:
raise HTTP(404)
Note, db.tables is a list of all the tables defined on the db connection object -- it is used in the SELECT() helper in the view to generate a <select> list of all the tables. The script in the view registers a jQuery event handler that fires whenever a different table is selected from the dropdown. The handler calls the web2py_component() function (which is in /static/js/web2py.js), which loads the form component via Ajax into the div with id="form". It appends the value of the selected table to the URL.
In the controller, the form() function checks for the db table name in request.args(0). It then sets response.generic_patterns so the "generic.load" view will be allowed (by default, generic views are only enabled for local requests). Alternatively, you could define your own "form.load" view, or even use a different extension (e.g., "form.html").
Because the form is loaded as a web2py Ajax component, the form submission will be trapped and submitted via Ajax as well, so it will not result in a full page reload.

Request.Files missing input='file' on the page after partial update

I have an MVC2 page that includes the following
Left Image
Right Image
When I save this page, I should be able to look at Request.Files to get the two file referenced. But the list is empty.
On the other hand, if I look at Request.Form, the two fields (for BackFile and FrontFile) are present.
Now, this portion of the form is part of the form that is partially updated when other selections on the form are made.
When I have had javascript references in such cases, I have had to also update the javascript references whenever I did a partial update of the page.
But there is no javascript reference to the "input" buttons. Still, I'm wondering if somehow, the "system" is losing the connection between the fields and their buttons and consequently not associating the input fields with files.
I don't know how to get around this.
Specifically is there a way I can proceed by using the values in Request.Form to do the uploads?
First: You cannot use the values from the Request.Form
Second: Did you change the enctype of the form as below:
<form action="home/upload" enctype="multipart/form-data" method="post">
<input type="file" name="uploader"></input>
<input type="submit" value="Save"></input>
</form>
Thrid: I you have a form as above you can create an action method in the controller like below
public class HomeController
{
[HttpPost]
public ActionResult UploadPictures(int id, HttpPostedFileBase ProductPhotoFileUpload)
{
//handle file save
return View();
}
}
Forth: The partial update should not matter

Resources