I have used dynamic form widget. The form fields are shown in the image below. As you can see there is a check box named cancel. What I want is if the cancel check box is clicked, It will only requires the check number and will allow the rest to be empty. Without using dynamic form I can easily implement this using when and whenClient validators since I can get exactly the name of the checkbox.
The problem here is that the dynamic form generates this kind of name series for the checkboxes...
TblDvBub[0][is_cancelled][]
TblDvBub[1][is_cancelled][]
TblDvBub[2][is_cancelled][]
I think you could extract the name of is_cancelled checkbox using 'attribute.name' from 'whenClient' => 'function(attribute, value){}' argument. console.log that 'attribute' - there must be an object with 'name' property - there you may get the number (use regex) of current TblDvBub.
By the way why do you use multiple is_cancelled[] field - doesn't it already belong to particular TblDvBub subarray?
1) In the form, you must override fieldClass
<?php $form = ActiveForm::begin([
'fieldClass' => 'backend\widgets\ActiveField'
]); ?>
2) To override the method
<?php
class ActiveField extends \yii\widgets\ActiveField
{
protected function getClientOptions()
{
$attribute = Html::getAttributeName($this->attribute);
if (!in_array($attribute, $this->model->activeAttributes(), true)) {
return [];
}
$enableClientValidation = $this->enableClientValidation || $this->enableClientValidation === null && $this->form->enableClientValidation;
$enableAjaxValidation = $this->enableAjaxValidation || $this->enableAjaxValidation === null && $this->form->enableAjaxValidation;
if ($enableClientValidation) {
$validators = [];
foreach ($this->model->getActiveValidators($attribute) as $validator) {
/* #var $validator \yii\validators\Validator */
$js = $validator->clientValidateAttribute($this->model, $attribute, $this->form->getView());
if ($validator->enableClientValidation && $js != '') {
if ($validator->whenClient !== null) {
$js = "if (({$validator->whenClient})(attribute, value, '{$this->form->id}')) { $js }";
}
$validators[] = $js;
}
}
}
if (!$enableAjaxValidation && (!$enableClientValidation || empty($validators))) {
return [];
}
$options = [];
$inputID = $this->getInputId();
$options['id'] = $inputID;
$options['name'] = $this->attribute;
$options['container'] = isset($this->selectors['container']) ? $this->selectors['container'] : ".field-$inputID";
$options['input'] = isset($this->selectors['input']) ? $this->selectors['input'] : "#$inputID";
if (isset($this->selectors['error'])) {
$options['error'] = $this->selectors['error'];
} elseif (isset($this->errorOptions['class'])) {
$options['error'] = '.' . implode('.', preg_split('/\s+/', $this->errorOptions['class'], -1, PREG_SPLIT_NO_EMPTY));
} else {
$options['error'] = isset($this->errorOptions['tag']) ? $this->errorOptions['tag'] : 'span';
}
$options['encodeError'] = !isset($this->errorOptions['encode']) || $this->errorOptions['encode'];
if ($enableAjaxValidation) {
$options['enableAjaxValidation'] = true;
}
foreach (['validateOnChange', 'validateOnBlur', 'validateOnType', 'validationDelay'] as $name) {
$options[$name] = $this->$name === null ? $this->form->$name : $this->$name;
}
if (!empty($validators)) {
$options['validate'] = new JsExpression("function (attribute, value, messages, deferred, \$form) {" . implode('', $validators) . '}');
}
// only get the options that are different from the default ones (set in yii.activeForm.js)
return array_diff_assoc($options, [
'validateOnChange' => true,
'validateOnBlur' => true,
'validateOnType' => false,
'validationDelay' => 500,
'encodeError' => true,
'error' => '.help-block',
]);
}
}
?>
3) Validation can be used
<?php
'whenClient' => "function(attribute, value, form) {
$("form# " + form + " > attribute")
}"
?>
Related
I am creating one API. In that I want to show buyers info, urls for their files/ images, and count in response. I have 3 tables buyers(PK: buyers_id), filedocs(FK: buyers_id), give_credit_transaction_master(FK: buyers_id). In those tables common column is buyers_id.
CODE
public function index()
{
$filedocsObj = FileDoc::with(['relBuyers'])->where('is_active','1')->get();
//return $filedocsCount;
$info = [];
// $profile_urls=[];
// $aadhar_urls=[];
// $pan_urls=[];
// $transaction_count=[];
// $info = array();
for($i = 0; $i < count($filedocsObj); $i++){
$buyer = FileDoc::Join('buyers', 'file_docs.buyers_id', '=', 'buyers.buyers_id')
->where('file_docs.buyers_id',$filedocsObj[$i]->buyers_id)
->select(
'buyers.buyers_id',
'buyers.buyers_name',
'buyers.buyers_address',
'buyers.buyers_contact_number',
'buyers.buyers_aadhar_number',
'buyers.buyers_pan_number',
'file_docs.buyers_profile_image',
'file_docs.buyers_aadhar_file',
'file_docs.buyers_pan_file',
)
->first();
// $info = $buyer->toArray();
array_push($info, [
'info' => $buyer
]);
// $info[] = $buyer;
$existProfile = Storage::disk('local')->exists('public/uploads/profile_images/'.$filedocsObj[$i]->buyers_profile_image);
if (isset($filedocsObj[$i]->buyers_profile_image) && $existProfile) {
// $profile_urls[$i] = Storage::disk('public')->url('/uploads/profile_images/'.$filedocsObj[$i]->buyers_profile_image);
array_push($info, [
'profile_url' => Storage::disk('public')->url('/uploads/profile_images/'.$filedocsObj[$i]->buyers_profile_image)
]);
//$info[] = Storage::disk('public')->url('/uploads/profile_images/'.$filedocsObj[$i]->buyers_profile_image);
}
else
{
// $profile_urls[$i]="";
array_push($info, [
'profile_url' => ''
]);
// $info[] = "";
}
$existAadhar = Storage::disk('local')->exists('public/uploads/aadhar_files/'.$filedocsObj[$i]->buyers_aadhar_file);
if (isset($filedocsObj[$i]->buyers_aadhar_file) && $existAadhar) {
//$aadhar_urls[$i] = Storage::disk('public')->url('/uploads/aadhar_files/'.$filedocsObj[$i]->buyers_aadhar_file);
array_push($info, [
'aadhar_url' => Storage::disk('public')->url('/uploads/aadhar_files/'.$filedocsObj[$i]->buyers_aadhar_file)
]);
// $info[] = Storage::disk('public')->url('/uploads/aadhar_files/'.$filedocsObj[$i]->buyers_aadhar_file);
}
$existPan = Storage::disk('local')->exists('public/uploads/pan_files/'.$filedocsObj[$i]->buyers_pan_file);
if (isset($filedocsObj[$i]->buyers_pan_file) && $existPan) {
//$pan_urls[$i] = Storage::disk('public')->url('/uploads/pan_files/'.$filedocsObj[$i]->buyers_pan_file);
array_push($info, [
'pan_url' => Storage::disk('public')->url('/uploads/pan_files/'.$filedocsObj[$i]->buyers_pan_file)
]);
//$info[] = Storage::disk('public')->url('/uploads/pan_files/'.$filedocsObj[$i]->buyers_pan_file);
}
$buyerTransactions = GiveCreditTransactionMaster::where('buyers_id',$filedocsObj[$i]->buyers_id)->get();
array_push($info, [
'transaction_count' => count($buyerTransactions)
]);
// $transaction_count[$i] = count($buyerTransactions);
// $resultSet = array_merge($info,$profile_urls,$aadhar_urls,$pan_urls,$transaction_count);
}
return $this->sendResponse($info, 'Buyers retrieved successfully.');
// return $this->sendResponse($resultSet, 'Buyers retrieved successfully.');
// return $this->sendResponse(array("Info" => $filedocs->toArray(),"profile_path" => $profile_urls, "aadhar_urls" => $aadhar_urls, "pan_urls" => $pan_urls, "transactionCountArray" => $transactionCountArray), 'Buyers retrieved successfully.');
}
In above code, I have taken one array info in which I am pushing query result buyer , iteration result profile_url, aadhar_url, pan_url, and another query result counts transaction_count. And returning info array as response.
MY API response:
{
"success": true,
"data": [
{
"info": {
"buyers_id": 2,
"buyers_name": "uuu",
"buyers_address": "dfgfgf",
"buyers_contact_number": "8986665576",
"buyers_aadhar_number": "654654654545",
"buyers_pan_number": "tytyr43242",
"buyers_profile_image": "2_B_profile_lady_profile.png",
"buyers_aadhar_file": "2_B_aadhar_aadhar_card_image.png",
"buyers_pan_file": "2_B_pan_pan_image.jpg"
}
},
{
"profile_url": "http://localhost/storage/uploads/profile_images/2_B_profile_lady_profile.png"
},
{
"aadhar_url": "http://localhost/storage/uploads/aadhar_files/2_B_aadhar_aadhar_card_image.png"
},
{
"pan_url": "http://localhost/storage/uploads/pan_files/2_B_pan_pan_image.jpg"
},
{
"transaction_count": 2
},
{
"info": {
"buyers_id": 28,
"buyers_name": "lili",
"buyers_address": "hjkhkdfgf",
"buyers_contact_number": "7856564656",
"buyers_aadhar_number": "343435353545",
"buyers_pan_number": "trtre34343",
"buyers_profile_image": "28_B_profile_test_profile.png",
"buyers_aadhar_file": "28_B_aadhar_test_aadhar.jpg",
"buyers_pan_file": "28_B_pan_test_pan.jpg"
}
},
{
"profile_url": "http://localhost/storage/uploads/profile_images/28_B_profile_test_profile.png"
},
{
"aadhar_url": "http://localhost/storage/uploads/aadhar_files/28_B_aadhar_test_aadhar.jpg"
},
{
"pan_url": "http://localhost/storage/uploads/pan_files/28_B_pan_test_pan.jpg"
},
{
"transaction_count": 0
}
],
"message": "Buyers retrieved successfully."
}
But in above response I am getting info of particular buyer separately than profile_url, aadhar_url, pan_url, transaction_count. Also profile_url, aadhar_url, pan_url, transaction_count this are getting separately.
I want all parameters(info,profile_url, aadhar_url, pan_url, transaction_count) of one buyer should come in one {}. How can I get that type of response?
I tried a lot using array_push, array_merge etc. But not getting requied response.
Please help. Thanks in advance.
This will help you with your desired response. I have manged your function. make it try and let me know if it helps you thanks
public
function index()
{
$filedocsObj = FileDoc::with(['relBuyers'])->where('is_active', '1')->get();
//return $filedocsCount;
$info = [];
// $profile_urls=[];
// $aadhar_urls=[];
// $pan_urls=[];
// $transaction_count=[];
// $info = array();
foreach ($filedocsObj as $index => $filedocsObjInfo) {
$buyer = FileDoc::Join('buyers', 'file_docs.buyers_id', '=', 'buyers.buyers_id')
->where('file_docs.buyers_id', $filedocsObjInfo->buyers_id)
->select(
'buyers.buyers_id',
'buyers.buyers_name',
'buyers.buyers_address',
'buyers.buyers_contact_number',
'buyers.buyers_aadhar_number',
'buyers.buyers_pan_number',
'file_docs.buyers_profile_image',
'file_docs.buyers_aadhar_file',
'file_docs.buyers_pan_file',
)
->first();
// $info = $buyer->toArray();
$info[$index]['info'] = $buyer;
// $info[] = $buyer;
$existProfile = Storage::disk('local')->exists('public/uploads/profile_images/' . $filedocsObjInfo->buyers_profile_image);
if (isset($filedocsObjInfo->buyers_profile_image) && $existProfile) {
$info[$index]['profile_url'] = Storage::disk('public')->url('/uploads/profile_images/' . $filedocsObjInfo->buyers_profile_image);
} else {
$info[$index]['profile_url'] = '';
}
$existAadhar = Storage::disk('local')->exists('public/uploads/aadhar_files/' . $filedocsObjInfo->buyers_aadhar_file);
if (isset($filedocsObjInfo->buyers_aadhar_file) && $existAadhar) {
$info[$index]['aadhar_url'] = Storage::disk('public')->url('/uploads/aadhar_files/' . $filedocsObjInfo->buyers_aadhar_file);
}
$existPan = Storage::disk('local')->exists('public/uploads/pan_files/' . $filedocsObjInfo->buyers_pan_file);
if (isset($filedocsObjInfo->buyers_pan_file) && $existPan) {
$info[$index]['pan_url'] = Storage::disk('public')->url('/uploads/pan_files/' . $filedocsObjInfo->buyers_pan_file);
}
$buyerTransactions = GiveCreditTransactionMaster::where('buyers_id', $filedocsObjInfo->buyers_id)->get();
$info[$index]['transaction_count'] = count($buyerTransactions);
// $transaction_count[$i] = count($buyerTransactions);
// $resultSet = array_merge($info,$profile_urls,$aadhar_urls,$pan_urls,$transaction_count);
}
return $this->sendResponse($info, 'Buyers retrieved successfully.');
// return $this->sendResponse($resultSet, 'Buyers retrieved successfully.');
// return $this->sendResponse(array("Info" => $filedocs->toArray(),"profile_path" => $profile_urls, "aadhar_urls" => $aadhar_urls, "pan_urls" => $pan_urls, "transactionCountArray" => $transactionCountArray), 'Buyers retrieved successfully.');
}
on PHP the following solution might work.
json_encode(array_merge(json_decode($a, true),json_decode($b, true)))
Try and let me know.
When you use an array_merge try json_decode your value like above.
I have a model with the following custom attributes topic_names, topic_details (string fields). I have also a model form with the custom attributes and custom rules. When I insert wrong data in the form fields, there is a model error, but it isn't displayed.
Model code:
......
public function rules()
{
return [
...
[['topics_names','topics_details'],'string'],
[['topics_names'],'checkCorrectAndSetTopics'],
];
}
public function checkCorrectAndSetTopics(){
if($this->topics_names AND $this->topics_details){
$topicsNamesArray = explode(',',$this->topics_names);
$topicsDetailsArray = explode(';',$this->topics_details);
if(sizeof($topicsNamesArray) !== sizeof($topicsDetailsArray)){
$this->addError('topics_names', \Yii::t('app', 'The topics names and details sets have different sizes'));
return FALSE;
}
}
return TRUE;
}
The problem is when the second rules is violeted, the form doesn't show any error, but there is. I checked it debugging the code below.
Form code:
..........
<?php
ActiveForm::$autoIdPrefix = createRandomId();//Function which creates a random id
$form = ActiveForm::begin(
['enableAjaxValidation' => true, "options"=> ["class"=>"extra-form"]]);
?>
<?= $form->errorSummary($model); ?>
<?= $form->field($model, 'topics_names')->textInput()
->label(\Yii::t('app', 'Topics Names'))?>
<?= $form->field($model, 'topics_details')->textarea(['rows' => 6])
->label(\Yii::t('app', 'Topics Details'))?>
........
Controller code:
public function actionAddExtraData($id){
if(!Yii::$app->request->isAjax){
throw new ForbiddenHttpException(\Yii::t('app','Cannot access this action directly.'));
}
$event = $this->findModel($id);
$extraData = ExtraData::find()
->andWhere(['event_id'=>$id])
->one();
if(!$extraData){
$extraData = new ExtraData();
$extraData->event_id = $id;
}else{
$extraData->prePerformForm();//Insert data on custom attributes
}
if(Yii::$app->request->isPost AND Yii::$app->request->isAjax AND Yii::$app->request->post("submitting") != TRUE
AND $extraData->load(Yii::$app->request->post())){
Yii::$app->response->format = Response::FORMAT_JSON;
$validation = ActiveForm::validate($extraData);
return $validation;
}
if ($extraData->load(Yii::$app->request->post()) && $extraData->save()) {
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ["success" => TRUE];
} else {
return $this->redirect(Yii::$app->request->referrer);
}
}
return $this->renderAjax('_event_extra_form',['model'=>$extraData,'event'=>$event]);
}
First thing, pretty sure you don't need to return true or false, you just need to add error. Second thing, in your example you name the attribute, you can actually get this when defining the function, so your function could look something like this
public function checkCorrectAndSetTopics($attribute, $model){
if($this->topics_names AND $this->topics_details){
$topicsNamesArray = explode(',',$this->topics_names);
$topicsDetailsArray = explode(';',$this->topics_details);
if(sizeof($topicsNamesArray) !== sizeof($topicsDetailsArray)){
$this->addError($attribute, \Yii::t('app', 'The topics names and details sets have different sizes'));
}
}
}
I want to dynamically fill in my form (see picture)
countries states and cities
The states select (html tag) is populated with a json file by the javascript function :
function onChangeCountries(countries, states) {
$(countries).on("change", function(ev) {
var countryId = $(this).val();
if (countryId != '') {
states.empty();
states.append('<option selected="true" disabled>Choose state</option>');
states.prop('selectedIndex', 0);
$.getJSON(statesUrl, function (data) {
$.each(data['states'], function (key, entry) {
if (entry.country_id == countryId) {
states.append($('<option></option>').attr('value', entry.id).text(entry.name));
}
})
});
}
});
}
countries and states parameters correspond to the two firsts select.
This function populate the states select corresponding to the country selected. The same mechanism operates with the cities select.
Now I want to use Symfony 4, here is my form :
<?php
// src/Form/LocationType.php
namespace App\Form;
use App\Entity\Location;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class LocationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$countries = json_decode(file_get_contents("js/countries.json"), TRUE)['countries'];
$countriesChoices = array();
foreach($countries as $country) {
$countriesChoices[$country['name']] = $country['id'];
}
$states = json_decode(file_get_contents("js/states.json"), TRUE)['states'];
$statesChoices = array();
foreach($states as $state) {
$statesChoices[$state['name']] = $state['id'];
}
$cities = json_decode(file_get_contents("js/cities.json"), TRUE)['cities'];
$citiesChoices = array();
foreach($cities as $city) {
$citiesChoices[$city['name']] = $city['id'];
}
$builder
->add('country', ChoiceType::class, array(
'choices' => $countriesChoices
))
->add('area', ChoiceType::class, array(
'choices' => $statesChoices
))
->add('city', ChoiceType::class, array(
'choices' => array(
'Choose city' => $citiesChoices
))
->add('zip_code', TextType::class)
->add('street', TextType::class)
;
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => Location::class,
));
}
}
The problem here is that I can not fill in the choices depending on user inputs.
Also I'm receiving an OutOfMemoryException (there is more than 40 000 cities in cities.json).
Edit
After dlondero answer, I haven't resolve my problem, here is my new LocationType class :
<?php
// src/Form/LocationType.php
namespace App\Form;
use App\Entity\Location;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
class LocationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$countries = json_decode(file_get_contents("js/countries.json"), TRUE)['countries'];
$countriesChoices = array();
foreach($countries as $country) {
$countriesChoices[$country['name']] = $country['id'];
}
$builder
->add('zip_code', TextType::class)
->add('street', TextType::class)
->add('country', ChoiceType::class, array(
'choices' => $countriesChoices
))
->add('area', ChoiceType::class, array(
'choices' => array()
))
->add('city', ChoiceType::class, array(
'choices' => array()
))
;
$formModifierStates = function (FormInterface $form, $countryId = null) {
$statesChoices = array();
if (null !== $countryId) {
$states = json_decode(file_get_contents("js/states.json"), TRUE)['states'];
foreach($states as $state) {
if ($countryId == $state['country_id']) {
$statesChoices[$state['name']] = $state['id'];
}
}
}
$form->add('area', ChoiceType::class, array(
'choices' => $statesChoices
));
};
$formModifierCities = function (FormInterface $form, $stateId = null) {
$citiesChoices = array();
if (null !== $stateId) {
$cities = json_decode(file_get_contents("js/cities.json"), TRUE)['cities'];
foreach($cities as $city) {
if ($stateId == $city['state_id']) {
$citiesChoices[$city['name']] = $city['id'];
}
}
}
$form->add('city', ChoiceType::class, array(
'choices' => $citiesChoices
));
};
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($formModifierStates) {
$data = $event->getData(); // country id
$formModifierStates($event->getForm(), $data);
}
);
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) use ($formModifierCities) {
$data = $event->getData(); // state id
$formModifierCities($event->getForm(), $data);
}
);
$builder->get('country')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifierStates) {
// It's important here to fetch $event->getForm()->getData(), as
// $event->getData() will get you the client data (that is, the ID)
$country = $event->getForm()->getData();
// since we've added the listener to the child, we'll have to pass on
// the parent to the callback functions!
$formModifierStates($event->getForm()->getParent(), $country);
}
);
$builder->get('area')->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifierCities) {
// It's important here to fetch $event->getForm()->getData(), as
// $event->getData() will get you the client data (that is, the ID)
$state = $event->getForm()->getData();
// since we've added the listener to the child, we'll have to pass on
// the parent to the callback functions!
$formModifierCities($event->getForm()->getParent(), $state);
}
);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => Location::class,
));
}
}
After filling in the form, I've got the message : "The choice "..." does not exist or is not unique". The choice is refering to the id (value of option) of the city selected in the select.
The problem is that I can't figure out how to populate the city ChoiceType?
You'd need to load them dynamically based on the choice made for the previous select. Approach is a lot similar to your with JS.
You can see an example in the official documentation: Dynamic Generation for Submitted Forms.
this is a user.php controller
public function verifyLogin() {
if (isset($_POST["email"])) {
$e = $this->input->post("email");
$p = $this->input->post("pass");
$this->form_validation->set_rules("email", "email", "required|valid_email|xss_clean");
$this->form_validation->set_rules("pass", "password", "required|xss_clean");
if ($this->form_validation->run()) {
$data = array(
'select' => '*',
'table' => 'users',
'where' => "email = '$e' AND activated = '1'"
);
$checklogin = $this->query2->selectData($data);
if ($checklogin === FALSE) {
echo "quering userInfo fails. email is wrong or activation not done";
exit();
} else {
foreach ($checklogin as $row) {
$dbid = $row->id;
$dbusername = $row->username;
$dbpassword = $row->password;
$dbemail = $row->email;
if ($p === $dbpassword) {
$login_data = array(
'name' => $dbusername,
'email' => $dbemail,
'password' => $dbpassword,
'id' => $dbid,
'expire' => '86500',
'secure' => TRUE,
'logged_in' => TRUE
);
$this->input->set_cookie($login_data);
$this->session->set_userdata($login_data);
if ($this->session->userdata("logged_in")) {
$time = time();
$now = unix_to_human($time, TRUE, 'us');
$updateLogin = $this->query1->updateLogin($e, $now);
if ($updateLogin) {
echo "success";
} else {
echo 'update failed';
}
} else {
echo "session failed";
}
}else{
echo 'password incorrect';
}
}
}
} else {
echo "form validation fails";
}
} else {
$this->load->view('header');
$this->load->view('login');
$this->load->view('modal');
$this->load->view('footer');
}
}
this is model.php
public function selectData($data){
if(isset($data['direction'])){
$dir = $data['direction'];
}else{
$dir = "ASC";
}
if(isset($data['offset'])){
$off = $data['offset'];
}else{
$off = '0';
}
if(isset($data['select']) && isset($data['table'])){
$this->db->select($data['select'])->from($data['table']);
}
if(isset($data['where'])){
$this->db->where($data['where']);
}
if(isset($data['order_by_name'])){
$this->db->order_by($data['order_by_name'], $dir);
}
if(isset($data['limit'])){
$this->db->limit($data['limit'], $off);
}
$query = $this->db->get();
if($query){
$d = $query->result();
return $d;
}else{
return FALSE;
}
}
is this a good way of quering database?
i am new to mvc and i am reading everywhere about "fat models and this controllers"
what can be done to make it a good mvc architecture?
its only acceptable to echo out from the controller when you are developing:
if ($checklogin === FALSE) {
echo "quering userInfo fails.
if checking login is false then either show a view or go to a new method like
if ($checklogin === FALSE) {
$this->showLoginFailed($errorMessage) ;
the check login code in the controller is a great example of something that could be refactored to a model. then if you need to check login from another controller its much easier. putting the form validation code in a model would be another choice. often times when you are validating form code you are also inserting/updating to a database table -- so having all those details together in a model can make things easier long term.
"fat model" does not mean one method in a model that does a hundred things. it means the controller says -- did this customer form validate and insert to the database? yes or no? 3 lines of code.
the model has the code that is looking into the "fat" details of the form, validation, database, etc etc. say 50 or more lines compared to the 3 in the controller. but the methods in the model should still be clean: small and specific.
I'm trying to create an admin side form. Here i'm trying to select data from the database. Also i want to display it. But for some reason it's not working. Here's my controller code,
public function save()
{
if (Input::has('save'))
{
$rules = array('category_name' => 'required|min:1|max:50', 'parent_category' => 'required');
$input = Input::all();
$messages = array('category_name.required' =>'Please enter the category name.', 'category_name.min' => 'Category name must be more than 4 characters', 'category_name.max' =>'Category name must not be more than 15 characters!!!', 'parent_category.required' => 'Please Select Parent Category.',);
$validator = Validator::make($input, $rules, $messages);
if ($validator->fails())
{
return Redirect::to('admin/category/add')->withErrors($validator)->withInput($input);
}
else
{
$insert_db = CategoryModel::insert($input);
$selected_category = CategoryModel::select($input['category_name']);
}
}
}
and my CategoryModel.php is following.
public static function insert($values)
{
$insert = DB::table('add_category')->insert(array('category_name'=>$values['category_name'], 'parent_category'=>$values['parent_category']));
if(isset($insert))
{
echo 'inserted successfully';
}
else
{
echo 'Failed';
}
}
public static function select($values)
{
$insert = DB::table('add_category')->where('category_name' . '=' . $values['category_name']);
}