PhalconPHP - Add multiple checkboxes in form from model - php

I have got two models: Rooms and RoomAttributes. There is a many-many relation between them:
$this->hasManyToMany(
"id",
"RoomAttributes",
"roomID",
"attributesID",
"roomattributesrelation",
"id",
array('alias' => 'attributes')
);
Now I'm creating a form to add a new room and I want to have a list of all attributes as checkboxes. What is the best way to do this and how should I save my room model after?

Maybe something like this:
use Phalcon\Forms\Element\Select;
class RoomForm extends \Phalcon\Forms\Form {
$attr_arr = ['attr1_id' => 'attr1_name', 'N_id' => 'N_name'];
// or $attr_arr= array_column(RoomAttributes::find()->toArray(),'id','name')
$attributes = new Select(
'attributes[]',
$attr_arr ,
['multiple' => 'multiple'
]);
$this->add($attributes);
}
in controller
****
if($new_room->save()){
$attributes = $_POST['attributes'];
foreach ($attributes as $id){
$new_attribute = new RoomAttributes();
$new_attribute->roomID = $new_room->id;
$new_attribute->attributesID = $id;
$new_attribute->save();
}
}

Related

Laravel: Updating hasMany/BelongTo relation

I have a master table jobs with multiple location in separate table job_location. Now I am not able to update/delete, if extra rows found from job_location. Now why I am saying DELETE is because sync() did this, but it's related to many-to-many relation. I am new to laravel, just trying to get eloquent approach to achieve this, otherwise deleting all rows and inserting can be done easily OR updating each and delete remaining is also an option but I wonder Laravel has something for this.
In every request I get multiple job locations(with unchanged/changed city,phone_number,address) which is creating trouble.
Some codeshots:
Model: [Job.php]
class Jobs extends Model
{
protected $fillable = [
'job_id_pk', 'job_name','salary'
];
public function joblocation() {
return $this->hasMany('\App\JobLocation', 'job_id_fk', 'job_id_pk');
}
}
Model:[JobLocation.php]
class JobLocation extends Model
{
protected $fillable = [
'jobl_id_pk', 'job_id_fk','city', 'address', 'phone_number'
];
public function job() {
return $this->belongsTo('\App\Jobs', 'job_id_fk', 'job_id_pk');
}
}
Controller:[JobController.php]
function jobDetail() {
if($params['jid']) {
// update
$obj = \App\Jobs::find($params['jid']);
$obj->job_name = $params['name'];
$obj->salary = $params['salary'];
$obj->save();
} else {
// create new
$data = array(
'job_name' => $params['name'],
'salary' => $params['salary'],
);
$obj = \App\Jobs::create($data);
}
// don't bother how this $objDetail has associative array data, it is processed so
foreach ($params['jobLocations'] AS $key => $objDetail) {
$jobLoc = new \App\JobLocation;
$jobLoc->city = $objDetail['city'];
$jobLoc->phone_number = $objDetail['phone_number'];
$jobLoc->address = $objDetail['address'];
$jobLoc->job()->associate($obj);
$obj->jobLoc()->save($jobLoc);
}
}
In this approach I am able to save all job locations, but I am using same function to update also. Please tell how I can update jobLocations if present. I am ok to loose previous entries, but it would be good if previous gets updated and new get entered OR if we have extra entries they get deleted. I know sounds weird but still guide me a way.
Yea, you cannot use the same function, do this
$jobs = \App\Jobs::find($params['jid']);
foreach ($params['jobLocations'] as $key => $objDetail) {
$joblocation = $jobs->joblocation->where('jobl_id_pk', $objDetail['some_id'])->first();
//here update you job location
$joblocation->save();
}
Something like this:
Controller:[JobController]
public function jobDetail() {
if( !empty($params['jid']) ) {
// update
$job = \App\Jobs::find($params['jid']);
$job->job_name = $params['name'];
$job->salary = $params['salary'];
$job->save();
} else {
// create new
$data = array(
'job_name' => $params['name'],
'salary' => $params['salary'],
);
$job = \App\Jobs::create($data);
}
$locationDetails = !empty($params['jobLocations']) ? $params['jobLocations'] : [];
$jobLocations = array_map(function($location) use($job) {
$location = array_merge($location, [ 'job_id_fk' => $job->job_id_pk ]);
return \App\JobLocation::firstOrNew($location);
}, $locationDetails);
$job->jobLocations()->saveMany($jobLocations);
}

How to in view pass array data to controller with model(in one atribute) Yii

It is my view in Yii framework. i wanna pass from here array data to controller with only one model attribute or just array without model. how to do it?
<?php $i = 1; foreach ($images as $image):
CHtml::activeLabel($model, 'remove', array('for'=>'rm_'.$image))
CHtml::activeCheckBox($model,'remove',array('name'=>'Obyavlenie[remove]', 'id'=>'rm_'.$image)) // remove is array(attribute) to pass
CHtml::link($image, 'name', array()),$image);
in model
class Obyavlenie extends CActiveRecord
{
public $remove;// should get array from view
Try this
<?php echo CHtml::activeCheckBox($model,'remove',array('name'=>'Obyavlenie[remove]['.$image‌​.']', 'id'=>'rm_'.$image)) ?>
Use CheckBoxList for multiple values.
In view:
// 1. Set data list
$list = array();
foreach ($images as $image):
$list[ $image ] = CHtml::link($image,'#'); // Change [ $image ] unique identificator to determine image you need
endforeach;
// 2. Output checkboxes
CHtml::activeCheckBoxList($model,'remove',$list,array(
'template' => '{input} {label}'
));
In action:
$model = new Obyavlenie('removeImages');
if ( isset( $_POST['Obyavlenie'] ) ) {
$model->attributes = $_POST['Obyavlenie']
}
In model:
class Obyavlenie extends CActiveRecord {
public $remove;
public function rules(){
return array(
// ...
array( 'remove', 'type', 'type' => 'array', 'on' => 'removeImages' )
);
}
// other model's methods
P.S. Obyavlenie -> Advert

How to load selected values in multiple-dropdown in update view in yii?

I am new in yii. I have problem with fetching selected values in dropdown when updating the record.
I have dropdown with multiple selection of user's email.
When adding it is working fine, it allows me to select multiple values and can insert selected value's ids comma separated in database. But the problem is when i want to update the record it displays only 1 selected record.
Here is my code:
in my View file:
<div class="controls">
<?php echo $form->dropDownList($model, 'uid', $allUsers, array('class' => 'select2-me input-sel_large', 'multiple' => 'true', 'options' => array('' => array('selected' => true)))); ?>
<?php echo $form->error($model, 'uid') ?>
</div>
in my Controller file:
$model = new User;
$allUsers = $model->getAllUsers();
in my Model file:
public function getAllUsers() {
$arr = Yii::app()->db->createCommand()
->select('userEmail,pkUserID')
->from('tbl_user')
->queryAll();
$users = array();
if (is_array($arr)) {
foreach ($arr as $value) {
$users[$value['pkUserID']] = $value['userEmail'];
}
}
return $users;
}
Can anyone help?
Example. Hope this help you.
class YourForm extends CFormModel
{
public $uid = array(); // selected pkUserID's
}
//in action
$yourForm = new YourForm();
$yourForm->uid = array(1,2,3); // for example selected users with pk 1,2,3
$this->render('your_view', array('yourForm'=>$yourForm));
//view
/** #var CActiveForm $form */
/** #var YourForm $yourForm */
echo $form->dropDownList(
$yourForm,
'uid',
CHtml::listData(User::model()->findAll(array('order' => 'userEmail ASC')), 'pkUserID', 'userEmail'),
array('empty' => '', 'multiple'=>true))
)

using doctrine's dbal in symfony2 with forms

So I want to do the following:
I created a form class at /Form/Type/UserType.php
I have a table with a list of states (table named "states").
I want to show all of these states in a drop down menu.
What code should I use in the class UserType to show all the states?
I tried:
$request = new Request;
$conn = $request->get('database_connection');
$states = $conn->fetchAll('SELECT state_code, state_name FROM states');
$builder->add('state', 'choice', array(
'choices' => $states,
'required' => false,
));
but that gives me an error. Basically, I want to query all of the states from the table states, and create a drop down menu from all of these states.
You can create State entity, map it to states table and create a OneToMany relation with the User entity. Then in your UserType form $builder->add('state') should create dropdown field automatically. You also have to set data_class option to your User entity in getDefaultOptions method of UserType form.
#m2mdas has given you the correct object based answer. However, if all you really want to do is to store the state_code then what you have will almost work. You just need to get the connection right.
class MyType extends extends AbstractType
{
public function __construct($em) { $this->em = $em; }
public function buildForm(FormBuilder $builder, array $options)
{
$conn = $this->em->getConnection();
$statesx = $conn->fetchAll('SELECT state_code, state_name FROM states');
// Need to index for the choice
$states = array();
foreach($statesx as $state)
{
$states[$state['state_code']] = $state['state_name'];
}
$builder->add('state', 'choice', array(
'choices' => $states,
'required' => false,
));
...
// In your controller
$form = new MyType($this->getDoctrine()->getEntityManager());

Passing models in array format to views in YII

How can I pass the model in array format.
I want to pass models in this format from controller to view:-
Users[user_contact]=Contact
Users[user_contact][contat_city]=City
Users[user_contact][contact_state]=state
This is what I am doing
public function actionCreate() {
$user = new Users;
$presContact = new Contacts;
$presCity = new Cities;
$presState = new States;
$contactArr = array();
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if (isset($_POST['Users'])) {
$transaction = CActiveRecord::getDBConnection()->beginTransaction();
$contactArr = CommonFunctions::saveContact($_POST['Users']['user_pres_contact'],'user_pres_contact',$errorArr);
$presContact = $contactArr['contact'];
$presCity = $contactArr['city'];
$presState = $contactArr['state'];
$user->attributes = $_POST['Users'];
$user->user_pres_contact_id = $presContact->contact_id;
if($user->save()){
$transaction->commit();
$this->redirect(array('view', 'id' => $user->user_id));
} else {
$transaction->rollback();
}
}
$this->render('createUser', array(
'Users' => $user,
'Users[\'user_pres_contact\']'=>$presContact,
'Users[\'user_pres_contact\'][\'contact_city\']'=>$presCity,
'Users[\'user_pres_contact\'][\'contact_state\']'=>$presState,
));
}
I am able to access only $users but
I m not able to access $Users['user_pres_contact'] in the view
That's because you are assigning them as strings...
The correct way of doing things would be (btw, what you are asking for can't done literally, it is impossible to assign 2 values to one key):
$user = array(
'user_press_contact' => array(
'contact' => $presContact,
'city' => $presCity,
'state' => $presState,
),
);
$this->render('createUser', array(
'Users' => $user,
));
It will give you $Users['user_press_contact']['contact'] for the name in the view, etc.
You can use
$user->getAttributes() //it returns an array of data.
Hope that's usefull
It is possible to solve this using model relations? You can define a relation from the User model to the City model (e.g. naming it relation_to_city), then you can just assign the user model in the controller
$this->render('view', 'user'=>$user);
and access the city (from the view)
$user->relation_to_city

Categories