required field for other model's field in yii - frameworks

I need to store a record in First Model. It has around 10 fields. Now, I need to apply required rule for one field which i'm storing in SECOND model and I'm getting these values for this field from Third model.(it is a drop down field)
how can i make this field mandatory in yii??
can any one help please..
Many Thanks,

You can add additional attributes and rules to a model. You don't have to only use attributes that directly relate to fields in your database table. Let's look at a basic example. You have a user (User) table which has the following fields:
id
email
password
And you have another table which stores user profile (UserProfile) information which has the structure:
id
user_id
country
When the user creates their account, you would have a form that captures their information. Your User model would have rules like:
array('email, password', 'required'),
array('email', 'unique', 'message'=>'Email already in use'),
...
You can add an attribute for country to your User model like so:
class User extends CActiveRecord {
public $country;
...
And then in your rules you can add the new attribute:
array('email, password, country', 'required'),
array('email', 'unique', 'message'=>'Email already in use'),
...
The country attribute will now be a part of your User model. You can now add that to your form:
<?php echo $form->dropDownList($model,'country',CHtml::listData(Country::model()->findAll(),'id','country_name'),array('empty'=>'-- select a country --')); ?>
Now on your form submit, the $model->validate() method will validate the country field. You can save this manually to your second model (UserProfile), something like:
if(isset($_POST['User'])){
if ($model->validate()){
$user_profile = new UserProfile;
$user_profile->user_id = $model->id;
$user_profile->country = $model->country;
$user_profile->save();
...
Hopefully that answers your question.

Related

Wagtail form builder with additional constant fields

I have created a quiz with wagtail form builder, but I need the form to contain some fields which are constant. For example, I have the following:
Name
Email
Employee id
[form builder fields]
How do I integrate fields [1-3] in the form builder to show up on all quizzes?
A simple way to do this is to override the get_form_fields method on your FormPage model.
This method simply returns a query for all stored FormFields on the FormPage model. We can add instances of FormField as needed and this will make the fields available in the form (view). They will also be available in form reports and emails.
1 - Override get_form_fields in your FormPage class.
In myapp/models.py wherever you have defined your FormPage model, add the following:
class FormPage(AbstractEmailForm):
# ...additional FormPage fiels and content_panels
def get_form_fields(self):
# get form_fields as defined by the super class & convert to list
# otherwise returns queryset
fields = list(super(FormPage, self).get_form_fields())
# append instances of FormField - not actually stored in the db
# field_type can only be one of the following:
# 'singleline', 'multiline', 'email', 'number', 'url', 'checkbox',
# 'checkboxes', 'dropdown', 'multiselect', 'radio', 'date',
# 'datetime', 'hidden'
# Important: Label MUST be unique in each form
# `insert(0` will prepend these items, so here ID will be first
fields.insert(0, FormField(
label='Employee Name',
field_type='singleline',
required=False,
help_text="Employee's Name"))
fields.insert(0, FormField(
label='Employee Email',
field_type='email',
required=False,
help_text="Employee's Email"))
fields.insert(0, FormField(
label='Employee ID',
field_type='number',
required=False,
help_text="Employee's ID"))
return fields
Note: When creating our FormField instances, these are not stored in the database, but their responses will be. You should provide the attributes label, field_type, required and help_text.
2 - Ensure there are no label conflicts on existing Forms
If the form label 'Employee ID' is used already in a form - not sure what will happen but it will likely break things so check you do not have conflicts in existing form pages.
Note: If the label is the same, you will not loose your data from previous submissions. All data is stored for past submissions even if you change the FormFields in use.
3 - Override the label field on FormField with some validation
In myapp/models.py wherever you have defined your FormField model, add the following:
from django.core.exceptions import ValidationError
# ... other imports and then models
RESERVED_LABELS = ['Employee Name', 'Employee Email', 'Employee ID']
def validate_label(value):
if value in RESERVED_LABELS:
raise ValidationError("'%s' is reserved." % value)
class FormField(AbstractFormField):
# page = ...
# redefine 'label' field so we can ensure there will be no conflicts with constant fields
label = models.CharField(
verbose_name='label',
max_length=255,
help_text='The label of the form field, cannot be one of the following: %s.'
% ', '.join(RESERVED_LABELS),
validators=[validate_label]
)
RESERVED_VALUES should match the labels used in your FormPage model.
This creates a simple Django Field Validator to check that you will not have conflicting labels. It also adds some nice help text so users do not get confused.
4 - Migrate
You should also do a migrations as you have now changed the label field on the FormField model.

Laravel: When creating a record with relations, cannot insert foreign key into table

I am following this exercise of an "intermediate task list" from Laravel 5.2 documentations and have some difficulty understanding how this piece of code works.
$request->user()->tasks()->create([
'name' => $request->name,
]);
Question 1
Specifically, I am confused at the relation between the user() and tasks() methods. Why and how exactly can we make the user() and tasks() methods available from the $request object?
Question 2
I created a similar app and has Person and Country models. I want to pass the country_id input from a dropdown list, but I can't get the database updated, using the following code.
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|max:255',
'country_id' => 'required|max:3',
]);
$request->user()->people()->create([
'name' => $request->name,
'country_id' => $request->country_id,
]);
return redirect('/people');
}
Why is it that the country_id cannot be saved to the table? I tried changing the user() to country() but the error message says, "class Country" was not found. But why is the 'user()' in the tutorial available then? I am baffled.
The user() method of request is available if the user making the request is authenticated.
Since it uses User model it can also fetch the related model. For tasks() to work Task relationship must be defined in user model.
For country_id to be created(mass assigned) ensure its included in $fillable property of the People model
$fillable = ['country_id']
Please read Eloquent model relationship section in Laravel documentation.

Yii2 REST API fields (user?fields=id) does not work

I've got the REST API working with the user table provided in the base migration. I can "GET /users" just fine, but according to the docs, I should also be able to "GET /users?fields=id" and receive a response limited to the id fields.
But instead I get the full result set.
Under the topic Fields in Yii2 Guide it says;
// only returns field id and email, provided they are declared in fields()
http://localhost/users?fields=id,email
so you have to override the fields() function to get the expected result.
// explicitly list every field, best used when you want to make sure the changes
// in your DB table or model attributes do not cause your field changes (to keep API backward compatibility).
public function fields()
{
return [
// field name is the same as the attribute name
'id',
// field name is "email", the corresponding attribute name is "email_address"
'email' => 'email_address',
// field name is "name", its value is defined by a PHP callback
'name' => function ($model) {
return $model->first_name . ' ' . $model->last_name;
},
];
}

Getting from ToManyField to Model values

In django, I have two models - User and UserProfile. There may exist zero or one profiles for a particular user. I'm trying to include the information from the UserProfile model directly on the UserResource.
I would like to use the profile ToManyField, if it exists, to access the contents of the associated UserProfile model. I've tried a variety of things in dehydrate, including self.profile.get_related_resource(self) and UserProfile.objects.get(id=...), but I can't seem to find my way from the profile field to the model object. Can anybody help me out?
I'm still new to Python, Django, and Tastypie, so hopefully if I'm doing anything awful somebody will be kind enough to point it out.
The goal is to have JSON that looks like this:
{
resourceUri: /v1/users/1
date_of_birth: Jan 1, 1980
... etc
}
where date_of_birth is a property of the UserProfileResource. I don't want all of the fields from UserProfileResource, and I don't want the UserProfile to be a nested object in the response - I want some fields from UserProfileResource to be top-level fields in the response, so that they look like part of the User resource.
class UserResource(ModelResource):
profile = fields.ToOneField('foo.api.UserProfileResource', 'user', null=True)
class Meta:
queryset = User.objects.all()
resource_name = 'users'
allowed_methods = ['get']
#etc...
class UserProfileResource(ModelResource):
date_of_birth = ...
#etc
I assume you're using Django 1.4 and AUTH_PROFILE_MODULE?
Since the User:UserProfile relationship is 1:1 I would opt for the ToOneField instead. This will serialize as a URI pointer to your UserProfileResource (if one exists.) If you'd like the UserProfileResource field data inline with your UserResource, you can specify full=True in the ToOneField definition. With this method you should not need to override dehydrate.
Also, ensure that the second argument in the ToOneField definition is the User attribute which points to your UserProfile Django model. For example if you have OneToOneField(User, related_name='profile') in your Django model then this attribute should be profile.
class UserResource(ModelResource):
profile = fields.ToOneField('foo.api.UserProfileResource', 'profile',
full=True, null=True)
class Meta:
queryset = User.objects.all()
resource_name = 'users'
allowed_methods = ['get']
If what you're after are specific fields from the UserProfile instance mixed in with your User, you should be able to do something like this:
class UserResource(ModelResource):
date_of_birth = fields.DateField('profile__date_of_birth', null=True)
class Meta:
queryset = User.objects.all()
resource_name = 'users'
allowed_methods = ['get']
fields = ['userfields', 'gohere', 'date_of_birth']

Does the symfony form fields initialize to null if not visible

I have few fields on the form like name, description, timestamp.
Now in the form I am only displaying name and description but not timestamp.
public function __construct()
{
$this->setTimestamp(new \DateTime());
}
Now in my database, it is coming as null.
Either doctrine is not executing constructor or those fields are set to null when displayed in form.
Even though I am not displaying them.
You need put the timestamp field in your FormType.
If you don't need to show it, just hide the field and set default value.
Something like that:
$builder->add('timestamp', 'hidden', array(
'data' => new \DateTime(),
));
Don't forget {{form_rest(form)}} at end of the twig template to send all hidden fields.