Cakephp 3.0 taken data - php

Hi I'm a novice in cakephp
However, I'm trying to make my blog with cakephp 3.0 which is stable version. I got stuck not taken database show view.ctp
Controller => "ListjobsController.php"
<?php
namespace App\Controller;
class ListjobsController extends AppController{
public function jobdetail(){
$jobdetail = $this->Listjobs->find('all');
$this->set( compact('jobdetail'));
}
}
Model =>Table => "ListjobsTable.php"
<?php
namespace App\Model\Table;
use Cake\ORM\Table;
class ListjobsTable extends Table{
public function initialize(array $config){
$this->table('listjobs');
$this->displayField('title');
$this->primaryKey('id');
$this->belongsToMany('Users',[
'foreignKey' => 'user_id'
]);
}
}
Template => Listjobs => "jobdetail.ctp"
<p><?= pr($jobdetail);exit; ?></p>
it does not appear that the current database information:
Cake\ORM\Query Object
(
[sql] => SELECT Listjobs.id AS `Listjobs__id`, Listjobs.user_id AS `Listjobs__user_id`, Listjobs.type_id AS `Listjobs__type_id`, Listjobs.cate_id AS `Listjobs__cate_id`, Listjobs.title AS `Listjobs__title`, Listjobs.location AS `Listjobs__location`, Listjobs.description AS `Listjobs__description`, Listjobs.skillsrequired AS `Listjobs__skillsrequired`, Listjobs.companyname AS `Listjobs__companyname`, Listjobs.website AS `Listjobs__website`, Listjobs.email AS `Listjobs__email`, Listjobs.password AS `Listjobs__password`, Listjobs.created AS `Listjobs__created`, Listjobs.modified AS `Listjobs__modified` FROM listjobs Listjobs
[params] => Array
(
)
[defaultTypes] => Array
(
[Listjobs.id] => integer
[id] => integer
[Listjobs.user_id] => integer
[user_id] => integer
[Listjobs.type_id] => integer
[type_id] => integer
[Listjobs.cate_id] => integer
[cate_id] => integer
[Listjobs.title] => string
[title] => string
[Listjobs.location] => string
[location] => string
[Listjobs.description] => text
[description] => text
[Listjobs.skillsrequired] => text
[skillsrequired] => text
[Listjobs.companyname] => string
[companyname] => string
[Listjobs.website] => string
[website] => string
[Listjobs.email] => string
[email] => string
[Listjobs.password] => string
[password] => string
[Listjobs.created] => datetime
[created] => datetime
[Listjobs.modified] => datetime
[modified] => datetime
)
[decorators] => 0
[executed] =>
[hydrate] => 1
[buffered] => 1
[formatters] => 0
[mapReducers] => 0
[contain] => Array
(
)
[matching] => Array
(
)
[extraOptions] => Array
(
)
[repository] => App\Model\Table\ListjobsTable Object
(
[registryAlias] => Listjobs
[table] => listjobs
[alias] => Listjobs
[entityClass] => \Cake\ORM\Entity
[associations] => Array
(
[0] => users
)
[behaviors] => Array
(
)
[defaultConnection] => default
[connectionName] => default
)
)
I can not understand why the data in the database does not appear.
hope you can help me!!!

The find() method always returns a Query object, that is the reason you cannot see the results but only the SQL that is going to be executed. If you are just starting with cake 3 there are a couple nice way in which you can see what the results of a query are:
debug($this->Table->find('all')->toArray());
That will give you an array of entities that were fetched from the database, the output may still be a bit confusing for you if you are not use to the idea of entities. SO here is another trick:
// In bootstrap.php
function dj($data)
{
debug(json_encode($data, JSON_PRETTY_PRINT));
}
And then:
dj($this->Table->find('all'));

do change in controller
namespace App\Controller;
class ListjobsController extends AppController{
public function jobdetail(){
$jobdetail = $this->Listjobs->find('all');
$this->set('listjobs', $jobdetail);
$this->set('_serialize', ['listjobs']);
}
}
now you can display data at view

Write in the appController.php file:
public function initialize()
{
$this->loadModel('Listjobs');
}
This should solve your problem.

Related

How to arrange an array to saveAll in CakePHP?

It's a little complicated to explain the way that I got the data from the view, but it arrives correctly to the controller.
I have 3 models: TourOpcione (this always save only one record), and TourOpcionOficina and TourOpcionServicio (these can save one or more records at time, and they have a foreign key to TourOpcione).
My problem is that I don't know what's the correct way to arrange the data in my controller before to save that. I want to avoid to use a loop, so I wish to save it with saveAll, or saveAssociated, or if this is not the case, accept any other way.
The explains around internet are confused.
I'm using CakePHP 2.6
Actually this is the array that I had created:
array
(
[TourOpcione] => Array
(
[opcion] => 1
[numeroPersonas] => 4
[total] => 2038
[tour_prospecto_id] => 12
)
[TourOpcionOficina] => Array
(
[0] => Array
(
[oficina_id] => 1623
)
[1] => Array
(
[oficina_id] => 1624
)
)
[TourOpcionServicio] => Array
(
[0] => Array
(
[servicio_id] => 6068
)
[1] => Array
(
[servicio_id] => 6067
)
)
)
Thanks in advice.
UPDATE
At this point, the TourOpcione is the only model who save the data. The other 2 doesn't.
Where can be my problem?
My models are the next (each class in his own model):
class tour_opcione extends AppModel {
public $name = 'TourOpcione';
public $hasMany = array(
'TourOpcionServicio' => array(
'className' => 'TourOpcionServicio',
'foreignKey' => 'tour_opcione_id',
),
'TourOpcionOficina' => array(
'className' => 'TourOpcionOficina',
'foreignKey' => 'tour_opcione_id',
)
);
}
class tour_opcion_servicio extends AppModel {
public $name = 'TourOpcionServicio';
public $belongsTo = array(
'TourOpcione' => array(
'className' => 'TourOpcione',
'foreignKey' => 'tour_opcione_id'
)
);
}
class tour_opcion_oficina extends AppModel {
public $name = 'TourOpcionOficina';
public $belongsTo = array(
'TourOpcione' => array(
'className' => 'TourOpcione',
'foreignKey' => 'tour_opcione_id'
)
);
}

Session container not working in zf2?

I have seen many questions on StackOverflow and I have this code
use Zend\Session\Container;
class IndexController extends AbstractActionController {
public function indexAction() {
$userSession = new Container('user');
$userSession->username = 'Sandhya';
return new ViewModel();
}
}
When I am printing the $userSession container in the controller it is giving me this output
Zend\Session\Container Object (
[name:protected] => user
[manager:protected] => Zend\Session\SessionManager Object (
[defaultDestroyOptions:protected] => Array (
[send_expire_cookie] => 1
[clear_storage] =>
)
[name:protected] =>
[validatorChain:protected] =>
[config:protected] => Zend\Session\Config\SessionConfig Object (
[phpErrorCode:protected] =>
[phpErrorMessage:protected] =>
[rememberMeSeconds:protected] => 240
[serializeHandler:protected] =>
[validCacheLimiters:protected] => Array (
[0] => nocache
[1] => public
[2] => private
[3] => private_no_expire
)
[validHashBitsPerCharacters:protected] => Array (
[0] => 4
[1] => 5
[2] => 6
)
[validHashFunctions:protected] =>
[name:protected] =>
[savePath:protected] =>
[cookieLifetime:protected] => 2592000
[cookiePath:protected] =>
[cookieDomain:protected] =>
[cookieSecure:protected] =>
[cookieHttpOnly:protected] => 1
[useCookies:protected] => 1
[options:protected] => Array (
[gc_maxlifetime] => 2592000
)
)
[defaultConfigClass:protected] => Zend\Session\Config\SessionConfig
[storage:protected] => Zend\Session\Storage\SessionArrayStorage Object (
)
[defaultStorageClass:protected] => Zend\Session\Storage\SessionArrayStorage
[saveHandler:protected] =>
)
[storage:protected] => Array ( )
[flag:protected] => 2
[iteratorClass:protected] => ArrayIterator
[protectedProperties:protected] => Array (
[0] => name
[1] => manager
[2] => storage
[3] => flag
[4] => iteratorClass
[5] => protectedProperties
)
)
It means there is nothing like username...
But when I am printing the S_SESSION it gives me this output...
Array (
[__ZF] => Array (
[_REQUEST_ACCESS_TIME] => 1429081041.81
)
[user] => Zend\Stdlib\ArrayObject Object (
[storage:protected] => Array (
[username] => Sandhya
)
[flag:protected] => 2
[iteratorClass:protected] => ArrayIterator
[protectedProperties:protected] => Array (
[0] => storage
[1] => flag
[2] => iteratorClass
[3] => protectedProperties
)
)
)
There is a field username...
But when I am trying to get the $_SESSION in view it gives me the same output as above..
The problem is I am not able to get the username in both the container as well as in $_SESSION.
I need it in the controllers.
what can be the problem need help? Thank you.
I think you have to work on your configuration.
You have to setup a common SessionManager to manage handling of your session information.
Something like this:
$sessionConfig = new SessionConfig();
$sessionConfig->setOptions($config);
$sessionManager = new SessionManager($sessionConfig);
$sessionManager->start();
Container::setDefaultManager($sessionManager);
I would suggest registering your SessionManager config in your ServiceManager instance and then use it throughout the application.
'service_manager' => array(
'factories' => array(
'session_manager' => 'My\Factory\SessionManagerFactory'
)
)
You can then get your SessionManager in any controller:
$sessionManager = $this->serviceLocator->get('session_manager');
And if you create a new Container it will use your common/default SessionManager instance automatically so all will be managed in one place.
$userSession = new Container('user');
$userSession->getManager() === $this->serviceLocator->get('session_manager') // true
On how to register your session_manager I will refer to the official ZF2 documentation.
You can use the following code:
$userSession = new Container('user');
//To check the session variable in zf2:
if($userSession->offsetExists('username')){
//Your logic after check condition
}
This will return true or false on the basis of session exist or not.
//To get the value of session:
echo $user->offsetGet('username');
Above code will return the value of session index username.
Instead of $userSession->username = 'Sandhya'; you can use below code:
$user->offsetSet('username','Sandhya');
This is zf2 standard, which is used by session container in zf2.
you can just get your username from session in controllers.
$userSession = new Container('user');
$username = $userSession->username ;
var_dump($username); //Sandhya
it work for me . try it !

Cakephp, validate multiple models manually

I have a form that produces the following array upon submition (see below).
I am using this data in my controller to perform several operations, after which I save each one individually. (Saving them all at once is not an option).
What I would need to do is to find a way to validate each of this models.
I have tried already:
$this->Model->set($pertinentData);
$this->Model2->set($pertinentData);
if($this->Model->validates() && $this->Model2->validates()){
//Do whatever
}
This produces unaccurate results, says it validates when I can see it doesn't and viceversa.
Anybody has any idea of a viable option? Ain't there a way to create a tableless model where I can define validation rules for these fields like:
Order.package_id
User.first_name
etc...
Any idea is appreciated. Below the array that the form produces.
Thanks.
Array
(
[Order] => Array
(
[id] => 15
[package_id] => 1743
[tariff_id] => 5470
[tarjeta] => 332
[numero_tarjeta] => 121204045050
[vencimiento_tarjeta] => 10/20
[cod_tarjeta] => 170
[titular_tarjeta] => JESUS CRISTO
[tarjeta_nacimiento] => 22/04/1988
[tarjeta_pais] => Argentina
[tarjeta_provincia] => Buenos Aires
[tarjeta_ciudad] => Ciudad
[tarjeta_cp] => 1428
[tarjeta_calle] => Calle
[tarjeta_numero] => 1477
[tarjeta_piso] => 2
)
[User] => Array
(
[id] =>
[email] => bla8#gmail.com
[phone] => 1568134449
[first_name] => Jesus
[last_name] => Something
[documento_tipo] => dni
[dni] => 335556666
[nacionalidad] => argentino
[birthdate] => 22/04/2019
)
[OrdersCompanion] => Array
(
[1] => Array
(
[first_name] => Chango
[last_name] => Mas
[documento_tipo] => dni
[dni] => 445556666
[nacionalidad] => argentino
[birthdate] => 30/02/2010
)
[1] => Array
(
[first_name] => Chango
[last_name] => Mas
[documento_tipo] => dni
[dni] => 445556666
[nacionalidad] => argentino
[birthdate] => 30/02/2010
)
)
)
You can usea tableless model by defining $useTable= false in the model. Like this
public $useTable = false;
Define all your custom validation and, of course, your schema (since your model has no table you have to define manually the model schema). Then in your controller, you must first indicate that it has no model, and then declare the $model variable. This is to avoid the automatic model-controller binding of cakePHP, your controller would look like this
public $useModel = false;
$model = ClassRegistry::init('ContactOperation');
Now your model is related to your controller as you want, and you can easily make your custom validation, previously defined.
$model->set($this->request->data);
if($model->validates()) {
$this->Session->setFlash(_('Thank you!'));
// do email sending and possibly redirect
// elsewhere for now, scrub the form
// redirect to root '/'.
unset($this->request->data);
$this->redirect('/');
} else {
$this->Session->setFlash(_('Errors occurred.'));
// display the form with errors.
}
You can find more detail from here

Access protected object in array in PHP

I am trying to access the following and need to get the value of [vid] array cell.
FieldCollectionItemEntity Object
(
[fieldInfo:protected] =>
[hostEntity:protected] => stdClass Object
(
**[vid]** => 119
[uid] => 1
[title] => My Page Name
[log] =>
[status] => 1
[comment] => 1
[promote] => 0
[sticky] => 0
[vuuid] => 3304d1cf-e3cf-4c5a-884a-4abb565ddced
[nid] => 119
[type] => subpage
[language] => und
[created] => 1408621327
[changed] => 1408640191
[tnid] => 0
[translate] => 0
[uuid] => 39145013-6637-4062-96e7-1b4589609c4f
[revision_timestamp] => 1408640191
I tried the following, but I guess I don't have a clue from here:-
$mything = new myClass;
print $mything->accessObjectArray();
class myClass {
protected $var;
function accessObjectArray(){
return $this-> $var;
}
//other member functions
}
Update
I actually only have access to the variable $content which has the following multi-dimensional arrays. All I want is to get the array cell's value of [vid].
To do that, I could print $content["field_image_title"]["#object"] but after that it's protected. That's where I am wondering that how can I access this array. I unfortunately do not have access FieldCollectionItemEntity to include in my page.
On doing this:- I get the following output:-
print_r($content);
Array
(
[field_image_title] => Array
(
[#theme] => field
[#weight] => 0
[#title] => Image Title
[#access] => 1
[#label_display] => hidden
[#view_mode] => full
[#language] => und
[#field_name] => field_image_title
[#field_type] => text
[#field_translatable] => 0
[#entity_type] => field_collection_item
[#bundle] => field_image_collection
[#object] => FieldCollectionItemEntity Object
(
[fieldInfo:protected] =>
[hostEntity:protected] => stdClass Object
(
[vid] => 119
[uid] => 1
[title] => My Page Name
[log] =>
[status] => 1
[comment] => 1
[promote] => 0
[sticky] => 0
[vuuid] => 3304d1cf-e3cf-4c5a-884a-4abb565ddced
[nid] => 119
[type] => subpage
[language] => und
[created] => 1408621327
[changed] => 1408640191
[tnid] => 0
[translate] => 0
[uuid] => 39145013-6637-4062-96e7-1b4589609c4f
[revision_timestamp] => 1408640191
[revision_uid] => 1
"$this-> $var;" this mean variable variable, and this throw php notice undefined variable $var,
you have to use
return $this->var;
or
return $this->vid
what your are doing with this:
return $this-> $var;
is accessing a property named after what is contained in your $var variable which does not contain anything in the scope where it is defined. pass it as a function argument:
function accessObjectArray($var){
return $this-> $var;
}
print $mything->accessObjectArray('vid');
but in any event, that won't work either since (as mentioned by #MikeBrant) you have an object in your parent object properties. something like this might work better
$o = new FieldCollectionItemEntity() // assumes this will construct the object in the state you have posted it
$o->accessObjectArray('hostEntity')->accessObjectArray('vid');
note that the method accessObjectArray($var) must be defined in both objects for this to work
the idea of a protected property is to prevent what you want to actually happen. But! protected means that only the class and it's extending classes can access a value. Make your own class that extends the other one:
class myClass extends FieldCollectionItemEntity {
function accessParentProtectedVars($var){
return $this->hostEntity->$var;
}
//other member functions
}
then your accessObjectArray() function will be able to acces the protected property. note that it's hardcoded to access the hostEntity object.
but seriously, you may want to consult the creator of the other class and maybe you will devise a way to best manage this. My proposed solution is not that much of a good practice if I daresay.
Answer for Drupal members as rendered array in the question looks like Drupal array
I believe you don't need a new class at all, you only need to get node's objects. So, below one line will work for you.
$parent_node = menu_get_object();
Now, you can access by $parent_node->vid

CakePHP Issue with saveAll()

I'm having a problem with CakePHP's saveAll() I was hoping someone could shed some light on.
I have a form which collects information to be saved for two models... Person and Inquiry. I believe the data are being sent correctly, but it's simply not saving the Inquiry data. It's returning a validation error, but there is no validation set up in the Inquiry model, and if I remove 'deep' => true from the People controller, it saves those fields fine.
Data It Posts
Array
(
[Person] => Array
(
[first_name] => Test
[middle_name] =>
[last_name] => User
[gender] => M
[date_of_birth] => Array
(
[month] => 02
[day] => 07
[year] => 1994
)
[address] => 1234 Main St
[address_apt] =>
[address_city] => Somewhere
[address_state] => OH
[address_zip] => 304982
[address_country] => US
[phone_cell] => (555) 555-5555
[permission_to_text] => 1
[phone_home] => (555) 555-5556
[email_address] => test#user.com
[preferred_contact] => text_cell
[Inquiry] => Array
(
[admit_type] => FR
[admit_term] => FA2014
[parent_first_name] => Mom
[parent_last_name] => User
[parent_email] => mom#user.com
[hs_name] => Columbus Downtown High School
[hs_ceeb_id] => 365210
[hs_homeschooled] => 0
[hs_grad_year] => Array
(
[year] => 2014
)
[coll_name] =>
[coll_ceeb_id] =>
[coll_major] =>
[coll_year] =>
[admit_major] => 1
[admit_minor] => 4
)
[social_facebook] =>
)
)
Value of $this->Person->validationErrors after Posting
Array
(
[Inquiry] => Array
(
[hs_homeschooled] => Array
(
)
[coll_name] => Array
(
)
[coll_ceeb_id] => Array
(
)
[coll_major] => Array
(
)
[coll_year] => Array
(
)
)
)
Model - Inquiry
<?php
class Inquiry extends AppModel {
public $belongsTo = array('Person');
}
Controller
<?php
class PeopleController extends AppController {
public $helpers = array('Html', 'Form', 'Country', 'State', 'Major', 'Minor', 'Term');
public function index() {
if ($this->request->is('post')) {
$this->Person->create();
if ($this->Person->saveAll($this->request->data, array('deep' => true))) {
print_r($this->request->data);
$this->Session->setFlash(__('Your post has been saved.'));
return $this->redirect(array('action' => 'index'));
}
print_r($errors = $this->Person->validationErrors);
$this->set('errors', $errors = $this->Person->validationErrors);
$this->Session->setFlash(__('Unable to add.'));
}
}
}
Model::saveAll() is a wrapper of saveMany or saveAssociated.
Since you're not passing data in a numerical indexed array, i.e.
array(
0 => array(...),
1 => array(...),
)
it means saveAssociated is called. What you're apparently trying to do is to save a new Person together with the associations (Inquiry). If you read through the manual you'll come to this paragraph:
If neither of the associated model records exists in the system yet
(for example, you want to save a new User and their related Profile
records at the same time), you’ll need to first save the primary, or
parent model.
So you obviously need to save the Person first and then all associations.

Categories