Codeigniter: creating helper with associative array - codeigniter

I have a number of social networking links (about 5) in the footer of my site and I need to generate data for each of the anchor link’s TITLE and URL - and ICON (image).
It’s not really worth creating a new table for only 5 rows, so I’m thinking a helper might be a the answer - some sort of associative array.
However, I’m a bit unsure how to construct the helper’s array - and completely clueless as to how to loop the results in the view file.
Any help, or any links to useful examples, is greatly appreciated!

In your helper:
function footer_link_data()
{
return array(
array(
'title' => 'Facebook',
'url' => 'http://facebook.com',
'icon' => 'http://placehold.it/64x64'
),
array(
'title' => 'Twitter',
'url' => 'http://twitter.com',
'icon' => 'http://placehold.it/64x64'
),
array(
'title' => 'Pinterest',
'url' => 'http://pinterest.com',
'icon' => 'http://placehold.it/64x64'
),
);
}
In your view:
<?php
$links = footer_link_data();
foreach($links as $link): ?>
<?php echo $link['icon'] ?>
<?php
endforeach; ?>
Alternatively, you can just create the HTML statically. For 5 links having it generated dynamically is kind of pointless.

Related

Add array to cookie codeigniter

I am using code igniter. I have to make cart feature and I have to save product ids to cookie but I am not able to add array to cookie. My controller code to add cookie is
public function add_to_cart(){
$product_id = $this->uri->segment(3);
$cookie= array(
'name' => 'cookie_product',
'value' => $product_id,
'expire' => '3600',
);
$this->input->set_cookie($cookie);
var_dump($this->input->cookie('cookie_product',true));die;
}
$product_id has my product id for example 41 . need help !
You do not have to use cookies directly. Use cart library which will handle cookies for you.
https://www.codeigniter.com/userguide3/libraries/cart.html
$this->load->library('cart');
$data = array(
'id' => 'sku_123ABC',
'qty' => 1,
'price' => 39.95,
'name' => 'T-Shirt',
'options' => array('Size' => 'L', 'Color' => 'Red')
);
$this->cart->insert($data);
And to view items
<?php print_r($this->cart->contents()); ?>
Cart sounds like a good solution.
The reason why your original code wasn't working is you were trying to pass an array instead of breaking it into individual parameters.
If you did want to fix it, your code should be:
$this->input->set_cookie($cookie['name'], $cookie['value'], $cookie['expire']);
Incidentally, you can store an array in a cookie by using serialize and unserialize to store the cookie as a string instead of an array:
$this->input->set_cookie('cookie_product', serialize($cookie));
var_dump(unserialize($this->input->cookie('cookie_product',true)));

How to validate HTML response in post array in codeigniter

I am using tinymce for to add user cover letter related to the application.
This what my post array look like:
Array
(
[cover_letter] => <p>Test Cover Letter</p>
<ol>
<li>Need to save this data</li>
</ol>
<p><strong>Thanks</strong></p>
)
Simply I have used the require validation rule for this.
'candidate_cover_letter' => array(
array(
'field' => 'cover_letter',
'label' => 'Cover Letter',
'rules' => 'required'
)
)
I get the validation error regarding this like Cover Letter require.
I have two main problem:
How to validate HTML post array data
Is this best practice to save data like this? if no then how should i save this data?
First of all, in Codeigniter if we want to do form validations we need to go like this :
$config = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required',
'errors' => array(
'required' => 'You must provide a %s.',
),
)
);
$this->form_validation->set_rules($config);
You can refer here
so, your code here should be like this in the controller:
$config =array(
array(
'field' => 'cover_letter',
'label' => 'Cover Letter',
'rules' => 'required'
)
);
$this->form_validation->set_rules($config);
You can add extra fields in the $config like the example above.
Another thing that you asked, "How you should save the data ?"
I would suggest you to use a field in the database table with type "TEXT" and it should be okay for you.
After you hit submit you get redirected back to your controller somewhere. One way to utilize CI form validation is:
//look to see if you have post data
if($this->input->post('submit')){
//points to applications/config/form_validation.php (look at next chucnk to set form_validation.php)
if($this->_validate('cover_letter')){
//rest of your post logic
//get data to upload to database
$data = [
'cover_letter'=>$this->input->post('cover_letter'),
'user_id'=>$this->input->post('user_id')
];
//save data to database ..also this should be moved to a model
$this->db->insert('name of table to insert into', $data);
}
//if you post doesnt not get validated you will fall here and if you have this chucnk of code in the same place were you have the logic to set up the cover letter you will see a pink message that says what ever error message you set up
}
Set up form validation.php
<?php
$config = [
//set up cover letter validation
//$this->_validate('cover_letter') maps to here and checks this array
'cover_letter' => [
[
'field'=>'cover_letter',
'label'=>'Cover Letter Required',//error message to return back to user
'rules'=>'required'//field is required
],
//example to add additional fields to check
[
'field'=>'observations',
'label'=>'Observations',
'rules'=>'required'
],
],
]

Symfony Select2 on EntityType: do not load all choices in HTML

I have the following form. Both for device and parts, I want to suppress Symfony loading all the choices into the HTML as I am already using a Select2 hook to load the choices through Ajax, and adding choices adds a lot of bloat (there are over 4000 parts).
What should I do? I tried adding 'choices' => array(), which indeed serves an empty list, bu results in an invalid form, as this means that there are no valid available choices.
<?php
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('device', EntityType::class, array('label' => 'Toestel', 'class' => 'AppBundle:Device', 'choice_label' => function($device) {
return $device->getBrand()->getName().' '.$device->getName();
}))
->add('parts', EntityType::class, array('label' => 'Onderdelen', 'class' => 'AppBundle:Part', 'choice_label' => 'name', 'multiple' => true))
->getForm();
}
?>
Use a querybuilder instead. This will show you a good example:
http://symfony.com/doc/current/reference/forms/types/entity.html#using-a-custom-query-for-the-entities
I think you can figure it out from the above link...
OK EDIT #2 according to your comments:
Try using the 'choices' option shown below:
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('device', EntityType::class, array(
'label' => 'Toestel',
'class' => 'AppBundle:Device',
'choices' => $device->getBrand()->getName().' '.$device->getName(),
}))
->add('parts', EntityType::class, array(
'label' => 'Onderdelen',
'class' => 'AppBundle:Part',
'choice_label' => 'name',
'multiple' => true))
->getForm();
}
Not certain that this will work for you though, but it might.
The variable $device needs be passed in as the form options, or somewhere else as a variable that represents the object AppBundle:Device.
Try this and see if it works for you!
Edit #3:
Based on your comments. I understand what you mean by loading with AJAX. What are you using? Maybe 'onload' for the body? You don't show the code.
However, maybe the best solution then is a ChoiceType with an empty array. If the empty array doesn't work, try putting something in it.
Try these suggestions. I only did it for the 'device' drop down list, since I'm not sure which one(s) you need it for:
Null array:
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('device', ChoiceType::class, array(
'label' => 'Toestel',
'choices' => array(
//null
),
}))
->add('parts', EntityType::class, array(
'label' => 'Onderdelen',
'class' => 'AppBundle:Part',
'choice_label' => 'name',
'multiple' => true))
->getForm();
}
Array with garbage in it:
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('device', ChoiceType::class, array(
'label' => 'Toestel',
'choices' => array(
'Something' => true,
),
}))
->add('parts', EntityType::class, array(
'label' => 'Onderdelen',
'class' => 'AppBundle:Part',
'choice_label' => 'name',
'multiple' => true))
->getForm();
}
Try them!
Found a solution of sorts. It's not excellent but it beats loading over 4000 HTML option tags.
It was harder than I think it should've been, but with the alsatian/form-bundle, it works fine. Read More info on alsatian/form-bundle from the coder himself.
You're going to want to tweak it a bit though, especially if you're not using MongoDB. E.g. in the bundle's services.yml I had to comment out:
- [setDocumentManager,["#doctrine.odm.mongodb.document_manager"]]
And in order to even install it, you have to set minimum-stability in composer.json to dev - and in order not to break everything else, you should also set prefer-stable to true.
in order for it to work on my MySQL setup. Otherwise it's also not very good at setting options for the Select2 element. I was able to tweak AbstractRoutableType.php a bit so it could also take different request methods, but there's no advanced data parsing as you would need JavaScript for that (I don't think HTML data- properties can convey functions).
So in the end, I still have all those options configured in my Twig file, between <script> tags.

Yii vs Highcharts vs Ajax

here is a part of my view:
<?php
echo CHtml::dropDownList('al_ev_id', $model->al_ev_id,$listaDateAl,
array(
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('stat/ajaxStoricoSubDetails'),
'update'=>'#storicoSubDetails',
),
'class' => 'rowform',
));
...
?>
<div id="storicoSubdetails">
...
<?php
$this->Widget('ext.highcharts.HighchartsWidget', array(
'options'=>array(
'title' => array('text' => 'A title'),
'xAxis' => array(
'categories' => $model->streamLabel
),
'yAxis' => array(
'title' => array('text' => 'another title')
),
'series' => array(
array('name' => $model->labelGraph, 'data' => $model->streamData)
)
)
));
?>
...
</div>
the controller in the action 'ajaxStoricoSubDetails' reload the same $this->Widget('ext.highcharts.HighchartsWidget' etc, etc
the objective of this code is to update the starting x-value of the graph, modifying it with the dropdown
and here is my problem:
the first rendering of highcharts graph is ok; but, when I change the value in the DropDown, thus starting the ajax part, graph is not rendered
highcharts return an error 16 code, that means
Highcharts already defined in the page
in fact in the second rendering code (the ajax fired part) I find
<script src="http://code.highcharts.com/highcharts.js"></script>
that I think is the problem
is there any way to avoid this
Any other suggestions?
It's not the best long term solution, but...
If <script src="http://code.highcharts.com/highcharts.js"></script> is at the top of your page now, move it in <div id="storicoSubdetails"> instead.
That way the script reference should be overwritten when the ajax stuff reloads everything in the storicoSubdetails div, and you will only have 1 script reference on the page.

How to translate form labels in Zend Framework 2?

I'm not getting it!.. Can please someone explain, how to translate form labels? A simple example would be great.
Thank you in advance!
class Search\Form\CourseSearchForm
...
class CourseSearchForm extends Form {
...
public function __construct(array $cities) {
parent::__construct('courseSearch');
...
$this->add(array(
'name' => 'city',
'type' => 'Zend\Form\Element\Select',
'options' => array(
'label' => 'Stadt',
'value_options' => $this->cities,
'id' => 'searchFormCity',
),
));
...
}
}
view script /module/Search/view/search/search/search-form.phtml
<?php echo $this->form()->openTag($form); ?>
<dl>
...
<dt><label><?php echo $form->get('city')->getLabel(); ?></label></dt>
<dd><?php echo $this->formRow($form->get('city'), null, false, false); ?></dd>
...
</dl>
<?php echo $this->form()->closeTag(); ?>
<!-- The formRow(...) is my MyNamespace\Form\View\Helper (extends Zend\Form\View\Helper\FormRow); the fourth argument of it disables the label. -->
The module/Application/config/module.config.php is configured:
return array(
'router' => ...
'service_manager' => array(
'factories' => array(
'translator' => 'Zend\I18n\Translator\TranslatorServiceFactory',
),
),
'translator' => array(
'locale' => 'de_DE',
'translation_file_patterns' => array(
array(
'type' => 'gettext',
'base_dir' => __DIR__ . '/../language',
'pattern' => '%s.mo',
),
),
),
'controllers' => ...
'view_manager' => ...
);
I also edited my view and use the FormLabel view helper:
<dt><label><?php echo $this->formLabel($form->get('city')); ?></label></dt>
Furthermore I debugged the FormLabel at the place, where the tranlator is used (lines 116-120) -- seems to be OK.
But it's still not working.
EDIT
The (test) items for labels, I added to the de_DE.po file manually, are tranlated. The ZF2 side problem was actually, that I was using $form->get('city')->getLabel() instead of $this->formlabel($form->get('city')) in th view script.
The problem is now, that the labels are not added to the de_DE.po file. But it's not a ZF2 issue anymore, so I've accept Ruben's answer and open a new Poedit question.
Instead of using:
<?php echo $form->get('city')->getLabel(); ?>
You should use the formlabel view helper. This helper automatically uses your translator during rendering if you have inserted it in your ServiceManager. Most likely you will have it in your Application's module module.config.php:
'service_manager' => array(
'factories' => array(
'translator' => 'Zend\I18n\Translator\TranslatorServiceFactory',
),
),
'translator' => array(
'locale' => 'en_US',
'translation_file_patterns' => array(
array(
'type' => 'gettext',
'base_dir' => __DIR__ . '/../language',
'pattern' => '%s.mo',
),
),
),
Once you do use the formlabel view helper:
echo $this->formLabel($form->get('city'));
And of course make sure your translations are in your .po file.
i think your problem is that you label are not detected by poedit (or similar tool), so you have to add them manually to your poedit catalogs (.po)
to make your label strings detected by tools like poedit, your strings need to be used inside a translate() function or _() (other function can be added in Catalog/properties/sources keyword)
as the _() function is not user in ZF2 (today) so a tiny hack is to add a function like this in your index.php (no need to modify anything, this way, in poedit params):
// in index.php
function _($str)
{
return $str;
}
and in your code, just use it when your strings are outside of a translate function
//...
$this->add(array(
'name' => 'city',
'type' => 'Zend\Form\Element\Select',
'options' => array(
'label' => _('myLabel') , // <------ will be detected by poedit
'value_options' => $this->cities,
'id' => 'searchFormCity',
),
));
//...
or like this if you prefer
$myLabel = _('any label string'); // <--- added to poedit catalog
//...
'options' => array(
'label' => $myLabel ,
'value_options' => $this->cities,
'id' => 'searchFormCity',
),
#Ruben says right!
Me I use PoEdit to generate my *.mo files and to be sure to get all translations in the file, I create somewhere (in view for example) a file named _lan.phtml with all text to be translated :
<?php echo $this->translate("My label");
... ?>
Of course, Poedit has to be configured to find my keywords. check this to how to configure it
All solutions don't use the power of ZF2. You must configure your poedit correctly :
All things are here :
http://circlical.com/blog/2013/11/5/localizing-your-twig-using-zend-framework-2-applications

Resources