cakephp211 saving data erros (associated tables) - cakephp-2.1

I have two associated tables (customers hasmany commands) and this is my form:
<?php echo $this->Form->create('Customer');?>
echo $this->Form->input('Client.name', array('disabled' => true,'value' => 'francis'));
echo $this->Form->input('Command.0.the_date');
echo $this->Form->end(__('save'));?>
and this is my function:
public function add() {
if (!empty($this->request->data)) {
unset($this->Customer->Command->validate['customers_id']);
$this->Customer->saveAssociated($this->request->data);
}
}
But when i process to save data, nothing happens!
Why?
Thanks!

Please use this line on your controller
var $uses = array('Customer','Command');
public function add() {
if (!empty($this->request->data)) {
unset($this->Customer->Command->validate['customers_id']);
$this->Customer->saveall($this->request->data);
}
}

Related

table relationship and how to use it in laravel controller

so, I have 2 tables, stage and event. Stage hasMany event, and Event belongsTo Stage. And I want to show all stage and its event as json. Here is my code in controller:
public function getschedule(){
$schedule = Stage::all();
//$event = Event_schedule2020::all();
if (!$schedule) {
return response()->json(['msg'=>'Error not found','code'=>'404']);
}
foreach($schedule->events as $array){
$datax[] = [
'id'=>$array->id,
'time'=>$array->time,
'category'=>$array->category,
'type'=>$array->title,
'designer'=>$array->designer,
];
}
foreach ($schedule as $item) {
$jadwal[] = [
'id'=>$item->id,
'date'=>$item->date,
'place'=>$item->stage,
'data'=>$datax,
];
}
return response()->json($jadwal);
}
but I always get this error
the error
so, is there anything I can do about this?
You can utilize inbuilt functions to do what you want to. Laravel automatically transforms model into JSON, no need to built arrays with it.
public function getschedule() {
// tell laravel you want to eager load events
$stages = Stage::with('events')->get();
// laravel knows you loaded events and therefor you can just return it and it does the rest automatically
return response()->json($stages);
}
in your Stage model you have to create relationship like this
public function events()
{
return $this->hasMany('App\Event');
}
then in your Controller
public function getschedule(){
$schedules = Stage::with('events')->get()->toArray();
return response()->json($schedules );
}
your mistake is call events on a collection for solve this you can change foreach like followings :
public function getschedule(){
$schedules = Stage::all(); // I add a 's' to $schedule because is better set plural name;
if (!$schedule) {
return response()->json(['msg'=>'Error not found','code'=>'404']);
}
foreach($schedules as $schedule){
$datax = [];
foreach($schedule->events as $event){
$datax[] = [
'id'=>$event->id,
'time'=>$event->time,
'category'=>$event->category,
'type'=>$event->title,
'designer'=>$event->designer,
];
}
$jadwal[] = [
'id'=>$item->id,
'date'=>$item->date,
'place'=>$item->stage,
'data'=>$datax,
];
}
return response()->json($jadwal);
}
but above solution is not recommended because send many request to server in any foreach loop, following solution is better:
public function getschedule(){
$schedules = Stage::with('events')->get(); // only this difference with above soloution and the rest is the same
if (!$schedule) {
return response()->json(['msg'=>'Error not found','code'=>'404']);
}
foreach($schedules as $schedule){
$datax = [];
foreach($schedule->events as $event){
$datax[] = [
'id'=>$event->id,
'time'=>$event->time,
'category'=>$event->category,
'type'=>$event->title,
'designer'=>$event->designer,
];
}
$jadwal[] = [
'id'=>$item->id,
'date'=>$item->date,
'place'=>$item->stage,
'data'=>$datax,
];
}
return response()->json($jadwal);
}

How to fetch session data in codeigniter?

I am trying to create a login process using codeigniter framework. Form validation is working but there is a problem in session. I can't fetch username after "Welcome-".
controller : Main.php
<?php
class Main extends CI_Controller
{
public function login()
{
$this->load->view('login');
}
public function login_validation()
{
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required');
if ($this->form_validation->run())
{
$username = $this->input->post('username');
$password= $this->input->post('password');
//model
$this->load->model('myModel');
if ($this->myModel->can_login($username,$password))
{
$session_data = array('username' => $username);
$this->session->set_userdata('$session_data');
redirect(base_url().'main/enter');
}
else
{
$this->session->set_flashdata('error','Invalid Username Or Password');
redirect(base_url().'main/login');
}
}
else
{
$this->login();
}
}
function enter()
{
if ($this->session->userdata('username')!=' ')
{
echo '<h2> Welcome- '.$this->session->userdata('username').'</h2>';
echo 'Logout';
}
else
{
redirect(base_url().'main/login');
}
}
function logout()
{
$this->session->unset_userdata('username');
redirect(base_url().'main/login');
}
}
?>
Add session library in the constructor
<?php
class Main extends CI_Controller
{
public function __construct()
{
parent::__construct();
// Load form helper library
$this->load->helper('form');
// Load form validation library
$this->load->library('form_validation');
// Load session library
$this->load->library('session');
$username = $this->session->userdata('username');
if (empty($username)) {
redirect('main/logout');
}
}
}
Another method you can load the session library in autoload.php file
File location: application/config/autoload.php
$autoload['libraries'] = array('database', 'email', 'session');
I suggest a slight code rearrangement for enter() that provides a better test for the user name using a tiny bit less code.
function enter()
{
if(empty($this->session->userdata('username')))
{
//base_url() accepts URI segments as a string.
redirect(base_url('main/login'));
}
// The following code will never execute if `redirect()` is called
// because `redirect()` does not return, it calls `exit` instead.
// So, you do not need an `else` block
echo '<h2> Welcome- '.$this->session->userdata('username').'</h2>';
echo 'Logout';
}
empty() will be true for an empty string, NULL, False and a couple of other things. In this case, you are most interested in an empty string or NULL. (empty() documentation HERE.)
You might want to consider adding 'trim' to your validation rules because it strips empty whitespace from the input string. That will remove the possibility of someone trying to input a username using only space characters.
Otherwise, your code should work. If it does not then it's very likely you do not have CodeIgniter sessions configured properly. There are many session setup questions answered here on Stack Overflow that will help you get it running.

simple ajax form in cakephp 3.0

As JsHelper is no more in cakephp 3.0 so what i am doing is to save my form data into database using ajax
i just have two input fields.
my files are:
add.ctp
js.js
EmployeesController.php
add.ctp
$this->Form->create('Employees');
$this->Form->input('name', array('id'=>'name'));
$this->Form->input('age', array('id'=>'age'));
$this->Form->button('Add Info', array(
'type'=>'button',
'onclick'=>'infoAdd();'
));
$this->Form->end();
js.js
function infoAdd() {
var name=$("#name").val();
var age=$("#age").val();
$.get('/employees/info?name='+name+"&age="+age, function(d) {
alert(d);
});
}
EmployeesController.php
class EmployeesController extends AppController {
public $components=array('RequestHandler');
public function add() {
$emp=$this->Employees->newEntity();
if($this->request->is('ajax')) {
$this->autoRender=false;
$this->request->data['name']=$this->request->query['name'];
$this->request->data['age']=$this->request->query['age'];
$emp=$this->Employees->patchEntity($emp,$this->request->data);
if($result=$this->Employees->save($emp)) {
echo "Success: data saved";
//echo $result->id;
}
else {
echo "Error: some error";
//print_r($emp);
}
}
}
}
Note : my model only have not empty rule for both fields
all what i am doing is working fine but i dont think i m doing it in right way or as it should be.
please help me what i m missing and what i don't need to do.
Take away the autoRender line and serialize the data you want returned:
public function add() {
$data = [];
$emp=$this->Employees->newEntity();
if($this->request->is('ajax')) {
$this->request->data['name']=$this->request->query['name'];
$this->request->data['age']=$this->request->query['age'];
$emp=$this->Employees->patchEntity($emp,$this->request->data);
if($result=$this->Employees->save($emp)) {
$data['response'] = "Success: data saved";
//echo $result->id;
}
else {
$data['response'] = "Error: some error";
//print_r($emp);
}
}
$this->set(compact('data'));
$this->set('_serialize', 'data');
}
The serialize function tells Cake that it's not expecting the function to have a view, so autoRender is not needed (http://book.cakephp.org/3.0/en/views/json-and-xml-views.html).

Simple AJAX / JSON response with CakePHP

I'm new to cakePHP. Needless to say I don't know where to start reading. Read several pages about AJAX and JSON responses and all I could understand is that somehow I need to use Router::parseExtensions() and RequestHandlerComponent, but none had a sample code I could read.
What I need is to call function MyController::listAll() and return a Model::find('all') in JSON format so I can use it with JS.
Do I need a View for this?
In what folder should that view go?
What extension should it have?
Where do I put the Router::parseExtension() and RequestHandlerComponent?
// Controller
public function listAll() {
$myModel = $this->MyModel->find('all');
if($this->request->is('ajax') {
$this->layout=null;
// What else?
}
}
I don't know what you read but I guess it was not the official documentation. The official documentation contains examples how to do it.
class PostsController extends AppController {
public $components = array('RequestHandler');
public function index() {
// some code that created $posts and $comments
$this->set(compact('posts', 'comments'));
$this->set('_serialize', array('posts', 'comments'));
}
}
If the action is called with the .json extension you get json back, if its called with .xml you'll get xml back.
If you want or need to you can still create view files. Its as well explained on that page.
// Controller code
class PostsController extends AppController {
public function index() {
$this->set(compact('posts', 'comments'));
}
}
// View code - app/View/Posts/json/index.ctp
foreach ($posts as &$post) {
unset($post['Post']['generated_html']);
}
echo json_encode(compact('posts', 'comments'));
// Controller
public function listAll() {
$myModel = $this->MyModel->find('all');
if($this->request->is('ajax') {
$this->layout=null;
// What else?
echo json_encode($myModel);
exit;
// What else?
}
}
You must use exit after the echo and you are already using layout null so that is OK.
You do not have to use View for this, and it is your wish to work with components. Well all you can do from controller itself and there is nothing wrong with it!
Iinjoy
In Cakephp 3.5 you can send json response as below:
//in the controller
public function XYZ() {
$this->viewBuilder()->setlayout(null);
$this->autoRender = false;
$taskData = $this->_getTaskData();
$data = $this->XYZ->getAllEventsById( $taskData['tenderId']);
$this->response->type('json');
$this->response->body(json_encode($data));
return $this->response;
}
Try this:
public function listAll(){
$this->autoRender=false;
$output = $this->MyModel->find('all')->toArray();
$this->response = $this->response->withType('json');
$json = json_encode($output);
$this->response = $this->response->withStringBody($json);
}

codeigniter passing count_all_results to view

I'm using the count_all_results() function to return a user's number of languages spoken. But when I try to pass the number to the view, I keep getting a php undefined variable (for $lang_cnt). Below is my code:
Model
function countLanguages($id) {
$this->db->where('user_id', $id)->from('languages');
return $this->db->count_all_results();
}
Controller
function showLangCount() {
$data['lang_cnt'] = $this->language_model->countLanguages($id);
$this->load->view('lang_view', $data);
}
View
<p>This user speaks <?php echo $lang_cnt; ?> languages.</p>
One problem is that your model function takes two arguments:
function countLanguages($id, $cnt_languages)
But when you call it you are only passing one argument:
$this->language_model->countLanguages($cnt_languages);
And an even bigger problem, as Rocket points out, is that countLanguages doesn't return anything. Try this:
function countLanguages($id) {
$this->db->where('user_id', $id)->from('languages');
return $this->db->count_all_results();
}
Always check your model functions if they return value or not. Try this:
function showLangCount() {
if($this->language_model->countLanguages($id))
{
$data['lang_cnt'] = $this->language_model->countLanguages($id);
}
else
{
$data['lang_cnt'] = NULL;
}
$this->load->view('lang_view', $data);
}
Its better to use:
return $query->num_rows();
to return the number of rows effected...

Resources