I is not What is the problem, I made a simple blog in Croogo, the problem is it is not adding or modifying or delete, because Arabic language ??
function add in controller
`public function admin_add() {
$this->set('title_for_layout', __('Add Part'));
if (!empty($this->request->data)) {
$this->Part->create();
if ($this->Part->save($this->request->data)) {
$this->Session->setFlash(__('The Part has been saved'), 'default', array('class' => 'success'));
$this->redirect(array('action' => 'index'));//, $this->Part->id));
} else {
$this->Session->setFlash(__('The Part could not be saved. Please, try again.'), 'default', array('class' => 'error'));
}
}
}`
=>
model
`class Part extends AppModel {
public $name = 'Part';
var $belongsTo = array(
'Market' => array(
'className' => 'Market',
'foreignKey' => 'market_id',
)
);
protected $_displayFields = array(
'id',
'num_part',
'prix_part',
'prop_Pledge',
'prix_Pledge',
);
}
`
add view
<?php $this->extend('/Common/admin_edit'); ?>
<?php echo $this->Form->create('Part');?>
<fieldset>
<div class="tabs">
<ul>
<li><span><?php echo __('Part'); ?></span></li>
<?php echo $this->Layout->adminTabs(); ?>
</ul>
<div id="role-main">
<?php
echo $this->Form->label('num_part', 'العدد : ');
echo $this->Form->input('num_part',array('label' => false ));
echo $this->Form->label('prix_part', 'االمبلغ : ');
echo $this->Form->input('prix_part',array('label' => false ));
echo $this->Form->label('prop_Pledge', 'إقتراح التعهد : ');
echo $this->Form->input('prop_Pledge',array('label' => false ));
echo $this->Form->label('prix_Pledge', 'مبلغ التعهد : ');
echo $this->Form->input('prix_Pledge',array('label' => false ));
?>
</div>
<?php echo $this->Layout->adminTabs(); ?>
</div>
</fieldset>
<div class="buttons">
<?php
echo $this->Form->end(__('Save'));
echo $this->Html->link(__('Cancel'), array(
'action' => 'index',
), array(
'class' => 'cancel',
));
?>
</div>
message error : The requested address was not found on this server.
I don't think it is because of Arabic language because when you do :
echo $this->Form->label('prop_Pledge', 'إقتراح التعهد : ');
The second parameter is a text. I don't know which Cake version you're using but I think that the first field should be Part.prop_Pledge (Cake v3).
I suggest you to try to use debug() and exit to see where is the real problem or try to put remove arabic characters to see if this is the reason of you're problem.
Just a question where is your $this->Form->create() in view ?
line added to the database successfully but does not retoure to index
it displays an error message
Could you print the message error hello21 please ?
Hope this will help you.
Related
Goodnight (or good morning),
I trying to upload multiple files at the same time. I am following the cookbook instructions to build the solution. I always got first file (not and array of files).
Here is my view code...
<?php
/**
* #var \App\View\AppView $this
* #var \App\Model\Entity\Upload $upload
*/
?>
<div class="row">
<aside class="column">
<div class="side-nav">
<h4 class="heading"><?= __('Actions') ?></h4>
<?= $this->Html->link(__('List Uploads'), ['action' => 'index'], ['class' => 'side-nav-item']) ?>
</div>
</aside>
<div class="column-responsive column-80">
<div class="uploads form content">
<?= $this->Form->create($upload, ['type' => 'file']) ?>
<fieldset>
<legend><?= __('Add Upload') ?></legend>
<?php
echo $this->Form->control('name');
echo $this->Form->control('document_type_id', ['options' => $documentTypes]);
echo $this->Form->control('period_id', ['options' => $periods]);
echo $this->Form->control('user_id', ['options' => $users]);
echo $this->Form->control('documents', ['type' => 'file', 'label' => __('Choose PDF Files'), 'accept' => 'application/pdf', 'multiple' => 'multiple']);
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
</div>
</div>
</div>
And here is my controller code...
public function add()
{
$upload = $this->Uploads->newEmptyEntity();
if ($this->request->is('post')) {
$upload = $this->Uploads->patchEntity($upload, $this->request->getData());
if ($this->Uploads->save($upload)) {
if (!is_dir($this->Parameters->findByName('document_directory')->first()->toArray()['value'] )) {
mkdir($this->Parameters->findByName('document_directory')->first()->toArray()['value'], 0776, true);
}
$documents = $this->request->getData('documents');
$this->loadModel('Dockets');
$dockets = $this->Dockets->findByDocketStateId(1);
$documents_ok = 0;
$documents_nok = 0;
$dockets_without_document = 0;
foreach($documents as $documents_key => $document_to_save)
{
foreach($dockets as $dockets_key => $docket)
{
$contents = file_get_contents($document_to_save);
$pattern = str_replace('-', '', $pattern);
$pattern = str_replace('', '', $pattern);
$pattern = preg_quote($docket->cuit, '/');
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
$documentsTable = $this->getTableLocator()->get('Documents');
$document = $documentsTable->newEmptyEntity();
$document->upload_id = $upload->id;
$document->document_type_id = $upload->document_type_id;
$document->period_id = $upload->period_id;
$document->docket_id = $docket->id;
$document->user_id = $this->getRequest()->getAttribute('identity')['id'];
if ($documentsTable->save($document)) {
if (!is_dir($this->Parameters->findByName('document_directory')->first()->toArray()['value'] )) {
mkdir($this->Parameters->findByName('document_directory')->first()->toArray()['value'], 0776, true);
}
$fileobject = $this->request->getData('document');
$destination = $this->Parameters->findByName('document_directory')->first()->toArray()['value'] . 'document_' . $document->id . '.pdf';
// Existing files with the same name will be replaced.
$fileobject->moveTo($destination);
}
$this->Flash->error(__('The document could not be saved. Please, try again.'));
$documents_ok = $documents_ok + 1;
unset($dockets[$dockets_key]);
unset($documents[$documents_key]);
break;
}
}
}
if(!empty($documents)){
//print_r($documents);
$documents_nok = count($documents);
unset($documents);
}
if(!empty($dockets)){
$dockets_without_document = count($dockets);
unset($dockets);
}
$message = __('There were processed ') . $documents_ok . __(' documents succesfully. ') . $documents_nok . __(' documents did not math with a docket. And ') . $dockets_without_document . __(' active dockets ddid not not have a document.');
$this->Flash->success(__('The upload has been saved. ') . $message);
return $this->redirect(['action' => 'view', $upload->id]);
}
$this->Flash->error(__('The upload could not be saved. Please, try again.'));
}
$documentTypes = $this->Uploads->DocumentTypes->find('list', ['keyField' => 'id',
'valueField' => 'document_type',
'limit' => 200]);
$periods = $this->Uploads->Periods->find('list', ['keyField' => 'id',
'valueField' => 'period',
'limit' => 200]);
$users = $this->Uploads->Users->find('list', ['keyField' => 'id',
'valueField' => 'full_name',
'conditions' => ['id' => $this->getRequest()->getAttribute('identity')['id']],
'limit' => 200]);
$this->set(compact('upload', 'documentTypes', 'periods', 'users'));
}
Can you help me to understand what I doing wrong?
Thanks,
Gonzalo
When using PHP, multi-file form inputs must have a name with [] appended, otherwise PHP isn't able to parse out multiple entries, they will all have the same name, and PHP will simply use the last occurrence of that name.
echo $this->Form->control('documents', [
'type' => 'file',
'label' => __('Choose PDF Files'),
'accept' => 'application/pdf',
'multiple' => 'multiple',
'name' => 'documents[]',
]);
Furthermore the following line:
$fileobject = $this->request->getData('document');
should probably be more like this, as there a) is no document field and b) even if there were, you most likely wouldn't want to process the same file over and over again:
$fileobject = $documents[$documents_key];
Also make sure that you have proper validation in place for the uploaded files, even if you don't seem to use the user provided file information, you should still make sure that you've received valid data!
I have created a CommentManager plugin for adding comments in my posts. Adding the comment form in Posts/view.ctp file and the comment form action is redirecting to CommentManager/Comments/add.
The comments are saving properly but when saving empty form, that doesn't shows the validation error messages which i have written in CommentsTable and also the entered data has gone from the form.
CommentManager/src/Controller/CommentsController/add
public function add()
{
$ccomment = $this->Comments->newEntity($this->request->data);
if ($this->request->is('post')) {
$newData = ['post_id' => $this->request->params['pass'][0]];
$ccomment = $this->Comments->patchEntity($ccomment, $newData);
if ($this->Comments->save($ccomment)) {
$this->Flash->success('The comment has been saved.');
return $this->redirect($_SERVER['HTTP_REFERER']);
} else {
$this->Flash->error('The comment could not be saved. Please, try again.');
}
}
$this->set(compact('ccomment'));
return $this->redirect($_SERVER['HTTP_REFERER']);
}
CommentManager/src/Model/Table/CommentsTable
public function validationDefault(Validator $validator) {
return $validator
->notEmpty('body', 'Body contents required.')
->notEmpty('email', 'An email is required.')
->add('email', [
'format' => [
'rule' => [
'custom',
'/^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/'
],
'message' => 'Enter a valid email.'
]
]);
}
src/Template/Posts/view.ctp
<?php echo $this->Html->link('Back', ['action' => 'index']) ?>
<?php echo $this->element('check_login'); ?>
<br/>
<?php $img_path = DS.'webroot'.DS.'images'.DS.$post->image; ?>
<img src="<?php echo empty($post->image)?'':$img_path; ?>">
<h2><?php echo $post->title; ?></h2>
<p><?php echo $post->body; ?></p>
<p><small><?php echo $post->created->format('d M Y'); ?></small></p>
<h3>Comments:</h3>
<?php foreach ($comments as $comment) { ?>
<p><?php echo $comment->body; ?></p>
<?php } ?>
<?php
echo $this->Form->create(null, ['url' => ['plugin' => 'CommentManager', 'controller' => 'Comments', 'action' => 'add', $post->id]]);
echo $this->Form->input('body', ['type' => 'textarea', 'rows' => '5', 'cols' => '5']);
echo $this->Form->input('email');
echo $this->Form->button('Save');
echo $this->Form->end();
?>
Don't call newEntity() with an empty array. Inste of
$ccomment = $this->Comments->newEntity($this->request->data);
Do:
$ccomment = $this->Comments->newEntity();
And in in the call to patchEntity() pass the $this->request->data
Please check my code:
<?php
$base_url = array('controller' => 'postads', 'action' => 'search/category:sales');
echo $this->Form->create("Filter",array('url' => $base_url, 'class' => 'filter'));
?>
<?php echo $this->Form->input('minprice',array('type'=>'text','placeholder'=>'Min','label'=>false,'value'=>100));?>
<?php echo $this->Form->input('maxprice',array('type'=>'text','placeholder'=>'Max','label'=>false,'value'=>200));?>
<?php echo $this->Form->input('Go',array('type'=>'submit','label'=>false));?>
<?php echo $this->Form->end();?>
Controller
public function search(){
if(($this->request->is('post') || $this->request->is('put')) && isset($this->data['Filter'])){
//pr($this->data);exit;
foreach($this->data['Filter'] as $name => $value){
if($value){
$filter_url[$name] = urlencode($value);
}
}
//return $this->redirect($filter_url);
}
}
When i submit the page my URL looks like http://www.example.com/postads/search/minprice:100/maxprice:200
But i want to http://www.example.com/postads/search/category:sales/minprice:100/maxprice:200
Please solve my problem
Thanks
learnphp.in
You can try like this :
$base_url = array('controller' => 'postads', 'action' => 'search/sales/100/200');
in Controller :
public function search($category = '', $minPrice = '', $maxPrice = ''){
still a novice, but I am fighting with the paginator to limit my view to 10 records [properties] and to sort it on a field in the properties model. What am I doing wrong or miss in my code to get the paginator to control my view???
I have 2 models, Regions and Properties, a region has many properties, for example, my view is /region/view/13 This shows all properties for region 13.
The paginator is displaying the correct amount of properties, set the pages correct and all seems correct, but the paginator is not limiting my view, it just displays all properties by that region in one huge list instead of limit the view to 10 per page.
The sort per sleeps doesn't work either although the url in the browser seems to be ok.
/regions/view/13/sort:sleeps/direction:asc
/regions/view/13/sort:sleeps/direction:desc
Model:
<?php
App::uses('AppModel', 'Model');
/**
* Region Model
*
* #property Country $Country
* #property Property $Property
*/
class Region extends AppModel {
/**
* Display field
*
* #var string
*/
public $displayField = 'regionname';
/**
* belongsTo associations
*
* #var array
*/
public $belongsTo = array(
'Country' => array(
'className' => 'Country',
'foreignKey' => 'country_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
/**
* hasMany associations
*
* #var array
*/
public $hasMany = array(
'Property' => array(
'className' => 'Property',
'foreignKey' => 'region_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
}
Controller:
public function view($id = null) {
if (!$this->Region->exists($id)) {
throw new NotFoundException(__('Invalid region'));
}
$this->Region->recursive = 2; // related to associated model data, Region -> Properties -> PropertyImages
$options = array('conditions' => array('Region.' . $this->Region->primaryKey => $id));
$total = $this->Region->Property->find('count', array(
'conditions' => array('Property.region_id' => $id)
));
$this->set('total', $total); // Push to counter the view.
$this->set('region', $this->Region->find('first', $options)); // Push the properties to the view.
$this->paginate = array(
'limit' => 10,
'conditions' => array('Property.region_id' => $id),
);
$this->Region->Property->virtualFields['sleeps'] = 'Property.sleeps';
$this->set('regions', $this->paginate('Property'));
}
View:
<div class="paging">
<?php
echo $this->Paginator->prev('< ' . __('previous'), array(), null, array('class' => 'prev disabled'));
echo $this->Paginator->numbers(array('separator' => ''));
echo $this->Paginator->next(__('next') . ' >', array(), null, array('class' => 'next disabled')); ?>
</div>
<br>
<?php
echo $this->Paginator->counter(array(
'format' => __('Page {:page} of {:pages}, showing {:current} records out of {:count} total, starting on record {:start}, ending on {:end}'))); ?><br>
Total properties: <?php echo $total . "\n"; ?><br>
Sort by: <?php echo $this->Paginator->sort('sleeps'); ?>
<?php if (!empty($region['Property'])): ?>
<div class="regionviewfooter"></div>
<?php
$i = 0;
foreach ($region['Property'] as $property): ?>
<!-- We only need 1 image to show up -->
<?php foreach ($property['PropertyImage'] as $key =>$propertyImage): ?>
<div class="regionview">
<div class="regionviewleft">
<?php echo '<span style="font-size:12px;line-height:18px;font-weight:bold;">'; echo $this->Html->link(__($property['description']), array('controller' => 'properties', 'action' => 'view', $property['id'])); echo '</span>'; ?>
<div class="regionviewheader">Sleeps <?php echo $property['sleeps']; echo ' :: ' ?>
<?php
if ($property['minPrice'] == 0) {
echo 'Please call for prices';
} else {
echo 'Prices from ';
echo $this->Number->currency($property['minPrice'], 'GBP');
if ($property['maxPrice'] == 0) {
echo ' PW';
} else {
echo ' - ';
echo $this->Number->currency($property['maxPrice'], 'GBP');
echo ' PW';
}
}
echo '<span style="font-size:11px;line-height:18px;font-weight:normal;">'; echo ' :: ';
echo $this->Html->link(__('View Property'), array('controller' => 'properties', 'action' => 'view', $property['id'])); echo '</span>'; ?>
</div>
<?php echo ($property['shortDesc']); ?><br>
Add to my Enquiry List :: Property Ref. (<?php echo strtoupper($property['ref']); ?>)
</div>
<div class="regionviewright">
<!-- display image -->
<?php echo $this->Html->image(($propertyImage['filename']), array('alt' => ($propertyImage['description']),'width' => '150' ,'height' => '77')); $key ?>
<?php $key++; ?>
</div>
</div>
<div class="clear"></div>
<div class="regionviewfooter"></div>
<?php if ($key == 1) {
break; // Stop, we did 1 image.
}
?>
<?php endforeach; ?>
<?php endforeach; ?>
<?php endif; ?>
<br>Top of Page<br><br>
You're setting your paginated results to $regions, yet in your view, you're looping through and displaying $region (singular), which is a straight-up find() above, with recursive 2, which will pull all properties.
So - although there are many other things that need cleaned up with your code, for now, just use $regions (plural) instead of $region singular in your View.
when user enter the full url..i want to save only youtube id... pregmatch examine and extract video id and then it will be saved into database..the problem is how to make this pregmatch check and extract youtube id before save the full url
thanks for helping
// this is add() function in videos_controller
function add() {
if (!empty($this->data)) {
$this->Video->create();
if ($this->Video->save($this->data)) {
$this->Session->setFlash(__('The Video has been saved', true));
$this->redirect(array('action' => 'admin_index'));
} else {
$this->Session->setFlash(__('The Video could not be saved. Please, try again.', true));
}
}
$vcats = $this->Video->Vcat->find('list');
$this->set(compact('vcats'));
}
// this is add.ctp file
<div class="videos form">
<?php // echo $this->Form->create('Image');?>
<?php echo $form->create('Video'); ?>
<fieldset>
<legend><?php __('Add Video'); ?></legend>
<?php
echo $this->Form->input('vcat_id');
echo $this->Form->input('title');
$url= $this->Form->input('link');
echo $url
?>
</fieldset>
<?php echo $this->Form->end(__('Submit', true)); ?>
</div>
<div class="actions">
<h3><?php __('Actions'); ?></h3>
<ul>
<li><?php echo $this->Html->link(__('List Videos', true), array('action' => 'index')); ?></li>
<li><?php echo $this->Html->link(__('List Vcats', true), array('controller' => 'vcats', 'action' => 'index')); ?> </li>
<li><?php echo $this->Html->link(__('New Vcat', true), array('controller' => 'vcats', 'action' => 'add')); ?> </li>
</ul>
</div>
// we get the unique video id from the url by matching the pattern but where i put this code to match before save
preg_match("/v=([^&]+)/i", $url, $matches);
$id = $matches[1];
Here
function add() {
if (!empty($this->data)) {
$this->Video->create();
$url = $this->data['Video']['link'];
/*assuming you have a column `id` in your `videos` table
where you want to store the id,
replace this if you have different column for this*/
preg_match("/v=([^&]+)/i", $url, $matches);
$this->data['Video']['id'] = $matches[1];
//rest of the code
}
}
I guess a better place for it is in the Model's beforeSave or beforeValidate method:
class Video extends AppModel {
...
public function beforeSave() {
if (!empty($this->data[$this->alias]['link'])) {
if (preg_match("/v=([^&]+)/i", $this->data[$this->alias]['link'], $matches)) {
$this->data[$this->alias]['some_id_field'] = $matches[1];
}
}
return true;
}
...
}