Yii2 autocomplete no response - autocomplete

Am trying to display users list as mail.Here it is my code,but there is no response
<?php
$data = Users::find()
->select(['user_email as value', 'user_id as id'])
->asArray()
->all();
echo AutoComplete::widget([
'name' => 'user_email',
'id' => 'ddd',
'clientOptions' => [
'source' => $data,
'autoFill'=>true,
'minLength'=>'1',
'select' => new JsExpression("function( event, ui ) {
$('#user_mail_1').val(ui.item.id);
}")],
]);
?>
<?= $form->field($model, 'user_email')->HiddenInput(['id' => 'user_mail_1'])->label(false) ?>

You need to use label for display value of auto complete input value.
So, get user_email as label like as:
<?php
use yii\web\JsExpression;
$data = Users::find()
->select(['user_email as value', 'user_id as id', 'user_email as label'])
->asArray()
->all();
// OR try below query for get data.
$data = (new \yii\db\Query())
->select(["user_email as value", "user_email as label","user_id as id"])
->from('users u')
->all();
echo AutoComplete::widget([
'name' => 'user_email',
'id' => 'ddd',
'clientOptions' => [
'source' => $data,
'autoFill'=>true,
'minLength'=>'1',
'select' => new JsExpression("function( event, ui ) {
$('#".Html::getInputId($model, 'user_email')."').val(ui.item.id); // Html::gtInputId() get dynamic id of input field.
}")],
]);
?>
<?= $form->field($model, 'user_email')->hiddenInput()->label(false) ?>

Related

Cakephp 3 Not Recognizing Custom Validation Rule Method and Validation Messages Not Showing

First issue is I have the following validators and public function in my table
UsersTable.php
$validator
->scalar('name')
->maxLength('name', 45)
->requirePresence('name', 'create')
->notEmptyString('name', 'You must enter a name for the user.');
$validator
->add('name', 'custom', array('rule' => 'checkExistingUser', 'message' => 'This user already appears to be in the system.', 'on' => 'create'));
public function checkExistingUser($value,$context)
{
return $this->find('all', ['conditions' => ['Users.name' => $context['data']['name'], 'Users.user_type_id' => $context['data']['user_type_id']]])->count() < 1 ;
}
When I save the form below I receive the message "Method checkExistingUser does not exist". Why doesn't it recognize the method when it's clearly defined in the table model? Am I missing something?
add.ctp
<?php echo $this->Form->create($user);?>
<fieldset>
<legend><?php echo __('Add User'); ?></legend>
<?php
echo $this->Form->control('name', ['type' => 'text']);
echo $this->Form->control('user_type_id');
echo $this->Form->control('owner', array('type' => 'text', 'label' => "Owner Name"));
echo $this->Form->control('owner_contact', array('type' => 'text', 'label' => "Owner Contact (phone, email etc)"));
echo $this->Form->control('description', ['type' => 'textarea']);
echo $this->Form->control('ia_exception', array('type' => 'text', 'label' => "IA Exception Number"));
echo $this->Form->control('is_manual', array('type' => 'checkbox', 'label' => "Password Updated Manually"));
echo $this->Form->control('Environment', ['type' => 'select', 'multiple' => 'true', 'label' => 'Environment(s)']);
?>
</fieldset>
<div class="buttons">
<?php
echo $this->Form->button('Save', ['type'=> 'submit', 'name' => 'submit']);
echo $this->Form->button('Cancel', ['type' => 'button', 'name'=>'cancel', 'onClick' => 'history.go(-1);return true;']);
echo $this->Form->end();
?>
</div>
UsersController.php
function add() {
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->set('The user has been saved');
return $this->redirect(array('action' => 'index'));
} else {
$this->Flash->set('The user could not be saved. Please, try again.');
}
}
$userTypes = $this->Users->UserTypes->find('list');
$changeSteps = $this->Users->ChangeSteps->find('list');
$environments = $this->Users->Environments->find('list');
$this->set(compact('user','userTypes', 'changeSteps', 'environments'));
}
Second issue is when I try to submit my form to check that the validator is working correctly for an empty name field I don't receive the message 'You must enter a name for the user'. Instead I receive a message stating 'This field is required'. Why is it not showing my message from notEmptyString? And where is 'This field is required' coming from?
For the first issue, I had to add a provider in my validator.
I changed
$validator
->add('name', 'custom', array('rule' => 'checkExistingUser', 'message' => 'This user already appears to be in the system.', 'on' => 'create'));
To this
$validator
->add('name', 'custom', ['rule' => 'checkExistingUser', 'provider' => 'table', 'message' => 'This user already appears to be in the system.', 'on' => 'create']);
Be careful with custom methods for validation during patching, because Cake expects string to be returned, otherwise it will rendere default meassage.
So for example, if we use a custom validation function during patching
// in a Controller
$this->Users->patchEntity($user, $data, ['validate' => 'custom');
Same applies for closures.
// in UserTable.php
public function validationCustom(Validator $validator) {
$validator = $this->validationDefault($validator);
$validator
->minLength('password',8,'At least 8 digits');
$validator->add('password',
'strength_light',[
'rule' => 'passwordCheck',
'provider' => 'table',
'message' => 'At least a number and a capital letter'
]
);
return $validator;
}
public function passwordCheck ($value = "") {
return preg_match("/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#$%^&*-]).{8,}/",$value);
}
This will return default message and not the custom one ("At least..") because we set a callable not-cakephp function as rule for custom validation, so the message should be returned by the called function:
public function passwordCheck ($value = "") {
if (!preg_match("/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#$%^&*-]).{8,}/",$value))
return "At least a number and a capital letter";
}

Form Data Not Being Sent From View To Controller

So I'm trying to send a few pieces of data from a form in cake's form builder but for some reason none of the data being submitted is showing up when I print out $this->data or $this->request->data
I've tried creating the form myself and using cake's Form Builder and I need to send this data via POST. The data shows up if I send it as a GET parameter.
view.ctp
echo $this->Form->create(null, array('action' => 'downloadbgc', 'type' => 'get'));
echo $this->Form->input('userId', ['type' => 'text' , 'id' => 'userId', 'name' => 'userId', 'value' => $user->id]);
echo $this->Form->input('product_id', ['type' => 'hidden' , 'id' => 'product_id', 'name' => 'product_id', 'value' => $user->product_id]);
echo $this->Form->submit('Download PDF', array('class' => 'btn btn-icon btn-primary', 'title' => 'Download'));
echo $this->Form->end();
controller.php
...
public function downloadbgc() {
$this->autoRender = false;
print_r("Data: ");
print_r($this->data); die();
}
}
...
When printing this out I get Data: Array() instead of Array('userId' => X, 'product_id' => Y) And I'm positive that these values aren't null since they print to the console.
Use the FormHelper's create() in a correct way:
echo $this->Form->create(false, ['url' => 'downloadbgc']);
echo $this->Form->input('userId', ['type' => 'text' , 'id' => 'userId', 'name' => 'userId', 'value' => 123]);
echo $this->Form->input('product_id', ['type' => 'hidden' , 'id' => 'product_id', 'name' => 'product_id', 'value' => 4456]);
echo $this->Form->submit('Download PDF', array('class' => 'btn btn-icon btn-primary', 'title' => 'Download'));
echo $this->Form->end();
Like the Docs point out the create() method can take the Model as first parameter or false, if you want to access the data without Model. Also use the url option as action is deprecated
In your Controller you can then use $this->request->data to access your data.

yii2: Undefined variable: model

I am just starting Yii2 framework.
I want to create a dropdown list which is 1 to 10 and a submit button
Once select the option and click the button should go to next page to show the number I choose.
In my view file : index.php
use yii\widgets\ActiveForm;
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'QTY')->dropDownList(range(1, 10)) ?>
<?= Html::submitButton('Buy', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
Then when I go to the page it gave me 'Undefined variable: model' at dropdown list there.
What should I do to make it correct?
And what is the different between Html and CHtml?
Thanks.
this code is form.php not index.php.
because we can see, there are active form.
your model is undefined maybe you write the wrong code
this is example of controller index.php
public function actionIndex()
{
$searchModel = new PersediaanBarangSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
Html and Chtml is the same
in Yii1=CHtml
in Yii2=Html
This is ment to be pagination? If yes use default functionality of the grid view.
This goes to controller:
$query = Post::find()->where(['status' => 1]);
$provider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 10,
],
'sort' => [
'defaultOrder' => [
'created_at' => SORT_DESC,
'title' => SORT_ASC,
]
],
]);
return $this->render('path_to_view',['dataProvider'=>$provider]);
Read more
This goes to view:
GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
'id',
'name',
'created_at:datetime',
// ...
],
]);
Read more
Actually you model is not loaded, Please check below example.
public function actionIndex($id = Null)
{
$data=array();
$data['model'] = !empty($id) ? \app\models\YourModel::findOne($id) : new \app\models\YourModel();
return $this->render('index', $data);
}

$this->getRequest()->getPost() return empty array in magento back end form submission

I am creating a magento custom admin module and a form. I want update this form but not updating. In Controller, under SaveAction() I print $this->getRequest()->getPost() and get empty array. please help me. Below code for form declination..
protected function _prepareForm() {
$form = new Varien_Data_Form(array(
'id' => 'edit_form1',
'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'))),
'method' => 'post',
'enctype' => 'multipart/form-data'
)
);
$form->setUseContainer(true);
$this->setForm($form);
return parent::_prepareForm();
}
And Create a from filed set like
protected function _prepareForm() {
$form = new Varien_Data_Form();
$this->setForm($form);
$fieldset = $form->addFieldset('qbanner_form', array('legend' => Mage::helper('qbanner')->__('Art information')));
$fieldset->addField('name', 'text', array(
'label' => Mage::helper('catalog')->__('Product'),
'required' => false,
'name' => 'name',
));
$fieldset->addField('artist_name', 'text', array(
'label' => Mage::helper('catalog')->__('Artist Name'),
// 'name' => 'artist_name',
'value' => Mage::helper('catalog')->__('Art Name value'),
));
$fieldset->addField('bca_status', 'select', array(
'label' => Mage::helper('catalog')->__('Art status'),
'name' => 'bca_status',
'values' =>$this->_getAttributeOptions('bca_status'),
));
$fieldset->addField('reason', 'editor', array(
'name' => 'reason',
'label' => Mage::helper('catalog')->__('Reason'),
'title' => Mage::helper('catalog')->__('Reason'),
'style' => 'width:440px; height:300px;',
'wysiwyg' => true,
'required' => false,
));
$fieldset->addField('thumbnail', 'text', array(
'label' => Mage::helper('catalog')->__('Art status'),
'name' => 'thumbnail',
//'values' =>$this->_getAttributeOptions('thumbnail'),
//'renderer' => 'Qaz_Qbanner_Block_Adminhtml_Qbanner_Grid_Renderer_Image'
));
if (Mage::getSingleton('adminhtml/session')->getQbannerData()) {
$form->setValues(Mage::getSingleton('adminhtml/session')->getQbannerData());
Mage::getSingleton('adminhtml/session')->setQbannerData(null);
} elseif (Mage::registry('qbanner_data')) {
$form->setValues(Mage::registry('qbanner_data')->getData());
}
return parent::_prepareForm();
}
protected function _getAttributeOptions($attribute_code)
{
$attribute = Mage::getModel('eav/config')->getAttribute('catalog_product', $attribute_code);
$options = array();
foreach( $attribute->getSource()->getAllOptions(true, true) as $option ) {
$options[$option['value']] = $option['label'];
}
return $options;
}
Here my
SaveAction()
public function saveAction() {
echo print_r( $this->getRequest()->getPost());
}
I have tied verious post. Any ideas?
Common error for all. You just need to add form key to your form.
Just add this line below your form declaration.
<input type="hidden" name="form_key" value="<?php echo Mage::getSingleton('core/session')->getFormKey(); ?>" />
Like this
<form action="<?php echo Mage::helper("adminhtml")->getUrl("demo/adminhtml_demo/demo");?>" method="post" id="custom-payment-form" enctype="multipart/form-data">
<input type="hidden" name="form_key" value="<?php echo Mage::getSingleton('core/session')->getFormKey(); ?>" />
Add this. Now you can get parameters by $this->getRequest()->getPost().
you can get variable of post and get method in magento with $this->getRequest()->getParams(); getParams() method But if you want to get exactly some variable data then use getParam('id');
/magento/catalog/product/view/id/406/category/14
$this->getRequest()->getParam('id') // 406
$this->getRequest()->getParams(); //get all get and post variables

CakePHP 2.1 Contact Form in Element Won't Send

I have two contact forms in my CakePHP application -- one with its own Controller, Model, and View, and another one in an element that can be accessed as a "quick" contact form from the footer of every page on the site.
The code for both forms is the same. The element is intended to access the Controller and Model that the other form uses. However, the element is not submitting the data or sending the email, while the regular page works just fine.
Here is the MVC Code for the regular form that IS working:
<!-- Model: Model/Contact.php -->
<?php
class Contact extends AppModel {
var $name = 'Contacts';
public $useTable = false; // Not using the database, of course.
var $validate = array(
'name' => array(
'rule' => '/.+/',
'allowEmpty' => false,
'required' => true,
),
'email' => array(
'allowEmpty' => false,
'required' => true,
)
);
function schema() {
return array (
'name' => array('type' => 'string', 'length' => 60, 'class' => 'contact input'),
'email' => array('type' => 'string', 'length' => 60, 'class' => 'contact input'),
'message' => array('type' => 'text', 'length' => 2000, 'class' => 'contact input'),
);
}
}
?>
<!-- Controller: Controller/ContactsController.php -->
class ContactsController extends AppController
{
var $name = 'Contacts';
/* var $uses = 'Contact'; */
var $helpers = array('Html', 'Form', 'Js');
var $components = array('Email', 'Session');
public function index() {
if(isset($this->data['Contact'])) {
$userEmail = $this->data['Contact']['email'];
$userMessage = $this->data['Contact']['message'];
$email = new CakeEmail();
$email->from(array($userEmail));
$email->to('email#example.com');
$email->subject('Website Contact Form Submission');
$email->send($userMessage);
if ($email->send($userMessage)) {
$this->Session->setFlash('Thank you for contacting us');
}
else {
$this->Session->setFlash('Mail Not Sent');
}
}
}
public function contact() {
if(isset($this->data['Contact'])) {
$userEmail = $this->data['Contact']['email'];
$userMessage = $this->data['Contact']['message'];
$email = new CakeEmail();
$email->from(array($userEmail));
$email->to('email#example.com');
$email->subject('Website Contact Form Submission');
$email->send($userMessage);
if ($email->send($userMessage)) {
$this->Session->setFlash('Thank you for contacting us');
// $this->redirect(array('controller' => 'pages', 'action' => 'index'));
}
else {
$this->Session->setFlash('Mail Not Sent');
}
}
}
}
?>
<!-- View: Views/Contacts/index.ctp -->
<?
$main = 'contact';
$title = 'quick contact';
?>
<div style="border-bottom: solid 1px #ccc;">
<h1 style="position:relative; float:left;"><?php echo $main; ?></h1>
<h2 style="position:relative;float:left;margin-top:15px; color: #869c38"> • <?php echo $title;?></h2>
<br><br>
</div>
<div class="clear"><br></div>
<div id="interior-page">
<?php
echo $this->Form->create('Contact');
echo $this->Form->input('name', array('default' => 'name (required)', 'onfocus' => 'clearDefault(this)'));
echo $this->Form->input('email', array('default' => 'email (required)', 'onfocus' => 'clearDefault(this)'));
echo $this->Form->input('message', array('default' => 'message', 'onfocus' => 'clearDefault(this)'));
echo $this->Form->submit();
echo $this->Form->end();
?>
</div>
And here is the view for the quick contact form that is NOT working, located in an element displayed in the footer of the default layout:
<?php
echo $this->Form->create('Contact');
echo $this->Form->input('name', array('default' => 'name (required)', 'onfocus' => 'clearDefault(this)'));
echo $this->Form->input('email', array('default' => 'email (required)', 'onfocus' => 'clearDefault(this)'));
echo $this->Form->input('message', array('default' => 'message', 'onfocus' => 'clearDefault(this)'));
echo $this->Form->submit();
echo $this->Form->end();
?>
I tried different ways of changing the form action, but I couldn't figure that out.
Usually, cake "automagically" creates the action of the form based on where you call it from E.g. if called from the view Views/Contacts/index.ctp, it will set the action to /contacts/index. In case of an element, Cake can't really guess what you're trying to do, so you need to set the action manually:
$this->Form->create('Contact', array('action' => 'index'));
Or set the full URL alternatively:
$this->Form->create('Contact', array('url' => '/contacts/index'));
Make sure you're including the Contact model for use on every page you need to create that form. In your case, since it's in your layout, that likely means you should put it in your AppController, so every page has access to it.
You also need to specify where the form should submit to:
echo $this->Form->create('Contact', array(
'url' => array('controller'=>'contacts', 'action'=>'contact')
)
);
Off-note - You can combine the last 2 lines:
echo $this->Form->end('Submit');
This creates the submit button with text "Submit" and also closes the form.
Thanks for this! It helped me a lot.
Just a quick thing, you're sending the email twice.
Once here:
$email->send($userMessage);
And again here:
if ($email->send($userMessage))
The first instance ($email->send($userMessage)) isn't necessary.
Cheers